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 (Patriarch) 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

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: map array elements with single quotes
by AnomalousMonk (Archbishop) 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!