Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2018-04-19 14:39 GMT
Find Nodes?
    Voting Booth?