in reply to loop through values in a string and print " " around each value.

If you only want to extract the zip code then there is no need to modify the whole line:
while (<IN>){ next if /^#/; # extract $zip, leave line unmodified in $_ ( my $zip = ( split /,/ )[ 2 ] ) =~ tr/"//d; if ( I want this zip code){ . . . } else{ push (@zips,$_); close(ZIPS); } }
  • Comment on Re: loop through values in a string and print " " around each value.
  • Download Code

Replies are listed 'Best First'.
Re^2: loop through values in a string and print " " around each value.
by kevyt (Scribe) on Jan 12, 2007 at 03:06 UTC
    Actually, I need the zip and the city. I am saving all of it to print back to the file later but I wont be checking the other values against anything.
    If the city and zip are what I need. I save it and process a few things.
    else, if the zip and city are not what I am looking for, save it to an array.
    After reading the file, print the unused lines back to the file.
    After processing the values that I needed, I will print those lines back to the file with # at the beginning of the line so I wont process them again :)
      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",
        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

      If you only need the city and zip then:
      while (<IN>){ next if /^#/; # extract $zip, leave line unmodified in $_ my ( $city, $zip ) = ( split /,/ )[ 0, 2 ]; tr/"//d for $city, $zip; if ( I want this zip code){ . . . } else{ push (@zips,$_); close(ZIPS); } }