[GRLUG] Some perl help

Roberto Villarreal rvillarreal at mktec.com
Sat Jul 2 15:11:00 EDT 2011


On Sat July 2 2011 2:33:29 pm David Pembrook wrote:
> I'm fluent enough in perl to be dangerous.  I have a line from a csv
> file and I want the "columns" in an array without any quotes. Some
> columns have them, some don't so I can't count on their presence.
> 
> The quick and dirty way I came up with used a temp array and a counter
> and know that has to be a better way to handle this.
> 
>          while (<FILE>) {
> 
>              @temp_values2 = split(",", $_);
> 
>              $counter=0;
>              foreach $temp_val (@temp_values2) {
>                  $temp_val =~ s/"//g;
>                  $temp_values[$counter] = $temp_val;
>                  $counter++;
>              }
> 
>              ..... more code to process the line follows
> 
>          }
> 
> 
> I also see that $temp_values isn't reset each loop either and values
> from a previous line with more columns would still be present.  Any
> thoughts?
> 
> Thanks,
> Dave

If you 'my' your variable, it'll "reset" (foreach my $temp_val ....).  In perl 
terms, it will "lexically scope" your variable to that loop; it won't exist 
outside of the loop.  If you had used "use strict;", it would have enforced 
this (and I would recommend always running with that pragma).

Untested, but I think the cleaner version of what you were looking for is:

while ( <FILE> ) {
	my @values = split( ',' );
	#choice 1
	@values = map { s/"//g;$_ } @values;
	#choice 2
	s/"//g foreach @values;
	#Continue processing @values
}

Hope that helps,
Roberto
	


-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.



More information about the grlug mailing list