in reply to Printing Array with quote and comma

One way to do it:

use warnings; use strict; my @arr = qw(book dog cat); print "['", join( "','", @arr), "'];\n";

But I'm curious... why are you trying to reinvent the data dumper wheel?

HTH

Update: As reasonablekeith pointed out, the code above doesn't work as intended for empty arrays. While the map solutions are more elegant (IMO), this corrects the problem:

print "[", ( @arr2 ? "'" . join( "','", @arr2) . "'" : ''), "];\n";

Thanks and ++ for pointing out the error.

Replies are listed 'Best First'.
Re^2: Printing Array with quote and comma
by reasonablekeith (Deacon) on Oct 05, 2005 at 10:00 UTC
    This doesn't really work, as if the array contains no elements, your code will still print one empty element...
    [''];

    The map style solutions don't have this problem.

    As pointed out below, the map solutions would take more memory, as they are creating an extra copy of your array. If you don't mind updating your array however, you could quote the elements in-place before hand.

    my @arr = qw(book dog cat); s/.*/'$_'/ for @arr; print "[" . join(',', @arr) . "];\n";
    ---
    my name's not Keith, and I'm not reasonable.