Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Array to list with quoted items

by miguelele (Beadle)
on Jan 15, 2012 at 19:09 UTC ( #948011=perlquestion: print w/replies, xml ) Need Help??
miguelele has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I need to pass a perl array, converted to a string list, to a block of JavaScript in a TT Template, to create a JavaScript array

If I use $string_to_feed_javascript = join (", ", @perl_array);

$string_to_feed_javascript contains all items separated by commas, but this breaks JavaScript syntax because each alphanumeric value must be enclosed by quotes./p>

So How can I convert the array to a string this way?
Thank you in advance

Replies are listed 'Best First'.
Re: Array to list with quoted items
by repellent (Priest) on Jan 15, 2012 at 19:57 UTC
    You may have heard of JSON?

    use JSON::XS;
    my $string_to_feed_javascript = encode_json \@perl_array; print $string_to_feed_javascript; # string is UTF-8 encoded
Re: Array to list with quoted items
by johngg (Abbot) on Jan 15, 2012 at 21:56 UTC

    Combining a quoting construct in a map with a join seems to be less confusing to my eye.

    $str = join q{, }, map qq{"$_"}, @arr;



Re: Array to list with quoted items
by BrowserUk (Pope) on Jan 15, 2012 at 19:30 UTC

    Would this do?:

    @array = qw[a list of alphanumeric values 1 2 3 4 5 6 7 8 9];; $string = '"' . join( '", "', @array ) . '"';; print $string;; "a", "list", "of", "alphanumeric", "values", "1", "2", "3", "4 +", "5", "6", "7", "8", "9"

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

    The start of some sanity?

      Thank you all!!, in this case I prefer the first solution, just using join with the quotes and the commas.

      Nest step will be JSON, but it will be a major update, with better skills

Re: Array to list with quoted items
by JavaFan (Canon) on Jan 15, 2012 at 21:15 UTC
    $string_to_feed_javascript = do {$" = '", "'; qq{"@perl_array"}};
    This will do what you ask, although I expect it will break your Javascript in many interesting ways.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (15)
As of 2016-10-24 14:09 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (307 votes). Check out past polls.