in reply to Re: Parsing a file line by line until a certain indice in array
in thread Parsing a file line by line until a certain indice in array
Thank you very much for your help and insight, I am better understanding how to think when programming in Perl as well as the structure.
The file I am parsing, contains each volume on a separate line, but then at the bottom it repeats every line but without \n, which I believe is a side-effect of parsing all volumes at once with the script that I am using.
I wanted to make the pars0r subroutine skip printing the '$vol_to_parse got got' to STDOUT for every instance of john after the first.
Is the proper way in Perl to make another nested if statement inside the existing if statement under the pars0r subroutine? I was thinking to declare a counter to increment/count how many times it showed up and only print the first instance. Is there an easier way to skip every instance of john after the first instance?
Something like:
sub pars0r{ foreach my $volume (@raw_data) { if ($volume =~ /$vol_to_parse/) { my $counter++; if($counter <=1){ print "$vol_to_parse got got \n"; } elsif ( $counter > 1 ) { next; # or break; ? } } } }
Am I approaching the logic in this the wrong way?
This is my code so far, but it prints out the line 'john got got' 6 times as opposed to one, where did I go wrong?
#!/usr/bin/perl #Libraries use strict; use warnings; use Getopt::Long; #Globals and default arguments my $vol_to_parse = "john"; my $file_to_parse = "file1.txt"; my @raw_data; my $counter=0; #Main Program process_args(); open_sesame(); pars0r(); #Subroutines sub process_args{ GetOptions ( 'v=s' => \$vol_to_parse, 'h=s' => \$file_to_parse, ) or die "syntax: $0 -v <volume> -h <file>\n"; } sub open_sesame{ open(DAT, "<", $file_to_parse) || die "Could not open file! ($!)\n + +"; chomp(@raw_data = <DAT>); close(DAT); } sub pars0r{ foreach my $volume (@raw_data) { if ($volume =~ /$vol_to_parse/){ $counter++; } if ($counter >=1){ print "$vol_to_parse got got \n"; } elsif( $counter > 1){ next; } } }
Output is:
john got got john got got john got got john got got john got got john got got
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Parsing a file line by line until a certain indice in array
by liverpole (Monsignor) on Sep 05, 2009 at 21:52 UTC |