Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Array to list with quoted items

by miguelele (Beadle)
on Jan 15, 2012 at 19:09 UTC ( [id://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?

    useJSON::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 (Canon) 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;

    Cheers,

    JohnGG

Re: Array to list with quoted items
by BrowserUk (Patriarch) 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

      Regards
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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-04-16 07:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found