in reply to Parsing a file line by line until a certain indice in array
I think the main problem is that where you have:
if ($volume =~ $vol_to_parse) {
you really should have:
if ($volume =~ /$vol_to_parse/) {
since it's a regular expression.
Update: Thanks to AnomalousMonk below for pointing out that my "fix" above was incorrect, and for teaching me something new!
A couple of other suggestions, though:
You should get in the habit of using warnings (in addition to strict).
Note that you've got a lot of string concatenation which is unnecessary, due to the interpolation nature of quotation marks ("double quotes"). In general, everywhere you've got a <close-quotes> <dot> <open-quotes> combination, you can remove it without change to your functionality (but it's much easier to read!)
For example, you can change:
print "Using: "."vol: $vol_to_parse". " and " . "file: $file_to_parse" + . "\n";
to:
print "Using: vol: $vol_to_parse and file: $file_to_parse\n";
Finally, if you use $! after system calls like open, it will tell you the exact error you got (eg. "file not found", "permission error", etc.):
open(DAT, "<", $file_to_parse) || die "Could not open file! ($!)\n +";
There are numerous other issues that I'll address by example rather than explanation. Here's a stripped-down, cleaned-up and working version of your program:
#!/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; # 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/) { print "$vol_to_parse got got \n"; } } }
Feel free to ask other questions (of course), and keep up the good Perl learning!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Parsing a file line by line until a certain indice in array
by AnomalousMonk (Archbishop) on Sep 05, 2009 at 21:20 UTC | |
by sluggo (Novice) on Sep 06, 2009 at 19:03 UTC | |
by AnomalousMonk (Archbishop) on Sep 06, 2009 at 21:10 UTC | |
|
Re^2: Parsing a file line by line until a certain indice in array
by sluggo (Novice) on Sep 05, 2009 at 20:21 UTC | |
by liverpole (Monsignor) on Sep 05, 2009 at 21:52 UTC |