in reply to My first perl script is working, what did I do wrong?
Some suggestions below on how to improve the early part of your script.
1) Replace:
with:if ($#ARGV != 0) { print "One, and only one (not $#ARGV), command line parameter is +expected\n"; exit; }
When a script encounters an error it should exit with a non-zero value (a bald exit returns a zero exit value), a usage statement is conventional, and or die is idiomatic.@ARGV == 1 or die "usage: $0 inputfile\n";
BTW, you should rarely need to use the cumbersome $#array notation. Using it here is unnecessary and the code is clearer using @ARGV instead. Another example, from Perl Best Practices, chapter 5, "Use negative indices when counting from the end of an array" is to prefer $frames[-2] to $frames[$#frames-1] because it is easier on the eye and avoids the undesirable repetition of the variable name (DRY).
2) Replace:
with:my $inputFile=$ARGV[0];
Using shift makes maintenance easier if you later add or remove command line arguments because you don't need to manually shuffle the ARGV indices (which are "magic numbers").my $inputFile = shift;
3) Replace:
with:if ( not -e $inputFile) { die "$inputFile doesn't exist!!!\nExiting.\n"; }
Using -f is more precise than -e because the first argument must be a file (not a directory, say). Using or die is idiomatic and more concise.-f $inputFile or die "input file '$inputFile' does not exist.\n";
4) Replace:
with:open my $file, $inputFile or die "Could not open $inputFile: $!";
As for why the three-argument form of open is preferred, the old two-argument form of open is subject to various security exploits as described at Opening files securely in Perl.open my $file, '<', $inputFile or die "Could not open $inputFile: $!";
|
---|
In Section
Seekers of Perl Wisdom