http://www.perlmonks.org?node_id=113601


in reply to question about regex and using a scalar variable to store/call it

As I understand the question, it is how to store the regular expression in a variable (and use them later.)

Here is a quick example which uses a "junk" Apache log and IIS log (they each contain but three fields -- a number, a file, and a date.) You can work out the expressions for the real logs. *Smiles*

use strict; #-- Define variables my $mDate; my $mDoc; my $mFile; my $mNumber; my $mSystem = 'apache'; my @mDocuments = ( 'report.html', 'secret.html' ); my %mLogExpr = ( apache => '^(\d+)\s*(\S+)\s*(\S+)$', iis => '^(\S+)\s*(\S+)\s*(\d+)$' ); my %mTotalDocs; #-- Initialize accumulators foreach (@mDocuments) { $mTotalDocs{$_} = 0; } #-- Process the information while (<DATA>) { #-- Parse line and skip non-matching ones next if ! /$mLogExpr{$mSystem}/; #-- Store the parsed values if ($mSystem eq 'apache') { ($mNumber, $mFile, $mDate)=($1,$2,$3); } else { ($mFile, $mDate, $mNumber)=($1,$2,$3); } #-- Since I am not doing anything with the information, #-- I am going to print it. *Smiles* print "Number:\t", $mNumber, "\n"; print "File:\t", $mFile, "\n"; print "Date:\t", $mDate, "\n"; print "\n"; #-- Check for documents foreach $mDoc (@mDocuments) { $mTotalDocs{$mDoc}++ if /$mDoc/; } } #-- Print the results foreach (@mDocuments) { print "Total for $_: $mTotalDocs{$_}\n"; } __DATA__ #Apache Log 123 report.html 2001-09-16 123 report.html 2001-09-17 234 nothing.html 2001-09-18 123 report.html 2001-09-18 345 secret.html 2001-09-19 567 stuff.html 2001-09-20 # IIS log report.html 2001-09-16 123 report.html 2001-09-17 123 nothing.html 2001-09-18 234 report.html 2001-09-18 123 secret.html 2001-09-19 345 stuff.html 2001-09-20 567

You can switch the log back and forth (between apache and iis) by changing the one $mSystem variable.

Does this help?

Update

I forgot to mention this the first time, but I also noticed a couple of other things in your example:

Update #2

I need to start using next unless instead of next if ! *Grins*

  • Comment on Re: question about regex and using a scalar variable to store/call it
  • Download Code