I have the following program “Extract.pl”, which opens a file, finds the lines containing “warning….”, “info…”, “disabling…” then counts and prints the value and number of them. It is working ok.
What I want to do is to create command line arguments for each of the 3 matches – warning, disabling and infos and then run either of them from the command prompt.
Here is the code:
#!/usr/bin/perl
use strict;
use warnings;
my %warnings = ();
my %infos = ();
my %disablings = ();
open (my $file, '<', 'Warnings.txt') or die $!;
while (my $line = <$file>) {
if($line =~ /^warning ([a-zA-Z0-9]*):/i) {
++$warnings{$1};
}
if($line =~ /^disabling ([a-zA-Z0-9]*):/i) {
++$disablings{$1};
}
if($line =~ /^info ([a-zA-Z0-9]*):/i) {
++$infos{$1};
}
}
close $file;
foreach my $w (sort {$warnings{$a} <=> $warnings{$b}} keys %warnings) {
print $w . ": " . $warnings{$w} . "\n";
}
foreach my $d (sort {$disablings{$a} <=> $disablings{$b}} keys %disablings) {
print $d . ": " . $disablings{$d} . "\n";
}
foreach my $i (sort {$infos{$a} <=> $infos{$b}} keys %infos) {
print $i . ": " . $infos{$i} . "\n";
}
The builtin special array
@ARGVholds all command line arguments to the script, excluding the script file itself (and the interpreter, if called asperl script.pl). In the case of a call likeperl script.pl foo bar warnings,@ARGVwould contain the values ‘foo’, ‘bar’, and ‘warnings’. It’s a normal array, so you could write something like (assuming the first argument is one of your options):I created flag variables for the three conditions before the main loop that goes through the file to avoid a regex compilation on every line of the file.
You could also use the
Getopt::LongorGetopt::Stdmodules. These provide easy and flexible handling of the command line arguments.