Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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'

Replies are listed 'Best First'.
Re: map array elements with single quotes
by ikegami (Pope) on Mar 10, 2010 at 07:24 UTC


    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 (Chancellor) 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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://827709]
Approved by ikegami
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (8)
As of 2018-05-21 16:09 GMT
Find Nodes?
    Voting Booth?