in reply to Re^2: loop through values in a string and print " " around each value.
in thread loop through values in a string and print " " around each value.

This works but I know there is a cooler way to do it :)
foreach (@zips){ @a = split /,/; foreach (@a){ print "\"" . $_ ."\","; } print "\n"; }
Output:
"Leesville","TX","78122","830","48177","Gonzales","P",

Replies are listed 'Best First'.
Re^4: loop through values in a string and print " " around each value.
by johngg (Canon) on Jan 12, 2007 at 10:36 UTC
    You probably don't want the trailing comma but it is easy to add back in with the solution below if required. The easiest way to print an array with a specific separator is to change the default list separator variable ($") from it's normal value of a space to the required character or string. This demonstrates the behaviour.

    $ perl -e' -> @l = (1, 2, 3); -> print @l, qq{\n}; -> print qq{@l\n}; -> $" = q{,}; -> print qq{@l\n};' 123 1 2 3 1,2,3 $

    Note that printing the array outside quotes just concatenates the elements together whereas inside quotes separates them with the default space and once we change the default to a comma, voila.

    In your particular case you also want to quote each field, which you can do in a map. We can create a new list to print, like this

    use strict; use warnings; my @flds = qw{Leesville TX 23432 67867 88 Bloggs F}; my @quotedFlds = map { qq{"$_"} } @flds; { local $" = q{,}; print qq{@quotedFlds\n}; }

    Note that I localise the change to $" in a small code block to avoid unexpected side-effects later in the script; localising changes like this is always good policy. Here's the output

    "Leesville","TX","23432","67867","88","Bloggs","F"

    I hope this is of use.

    Cheers,

    JohnGG