Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

map array elements with single quotes

by kalyanrajsista (Scribe)
on Mar 10, 2010 at 07:19 UTC ( #827709=perlquestion: print w/ replies, xml ) Need Help??
kalyanrajsista has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to assign single quotes to array elements with the following code, but is not doing what I wanted. Is map() suggestible or any other way to do it

use strict; my @foo = ('usa', 'cananda', 'strawberry'); @foo = map { "'$_',", @foo); print @foo; # printing as 'usa','cananda','strawberry', # instead of 'usa','cananda','strawberry'

Comment on map array elements with single quotes
Download Code
Re: map array elements with single quotes
by ikegami (Pope) on Mar 10, 2010 at 07:24 UTC

    join

    print(join(',', map "'$_'", @foo), "\n");

    But what about something with an apostrophe in it (say The People's Republic of China, since you're mostly listing countries). You should probably be using Text::CSV_XS

      First of all the way you used map is wrong . There is some unbalanced brace also . It should be like the following,
      use strict; use warnings; my @foo = ('usa', 'cananda', 'strawberry'); @foo = map { "'$_'"} @foo; print @foo;

        First of all, it would've been more appropriate for you to respond to the original post, not to ikegami's reply — he didn't use map the wrong way :)

        Next, while your observation is correct, you seem to have overlooked the fact that the original poster is getting an unwanted trailing comma.

        Your solution could be fixed by changing the output field separator $,

        ... $, = ","; print @foo;

        or (to keep the effect localized)

        ... { local $, = ","; print @foo; }
Re: map array elements with single quotes
by AnomalousMonk (Abbot) on Mar 10, 2010 at 18:55 UTC
    Is map() suggestible or any other way to do it ...

    map may or may not be suggestible, but it is dispensable. Since single-quotes are already being used when initializing the array, why not something like (although this won't work with "The People's Republic of China" – embedded whitespace):

    >perl -wMstrict -le "my @foo = qw('usa' 'canada' 'strawberry'); print join ',', @foo; " 'usa','canada','strawberry'

    Maybe getting rid of  map was not the point, but it is another way!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://827709]
Approved by ikegami
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (12)
As of 2014-12-26 12:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (171 votes), past polls