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.
A 'naked string' used as a regex will work just as well with the =~ and !~ binding operators as enclosing the string in // delimiters, as shown by the example below.
>perl -wMstrict -le "my $rx = 'x\dy'; for my $str (qw(xxy x23y x4y xy)) { print qq{match '$str'} if $str =~ $rx; print qq{no match '$str'} if $str !~ $rx; } " no match 'xxy' no match 'x23y' match 'x4y' no match 'xy'
The problem with using a string in that way (or within // delimiters) is that Perl is forced to re-compile the regex each time it is encountered (IIRC). This probably does not matter in a short script processing a short file, but it may matter if the file is 100,000,000 lines long!
The re-compilation problem can be avoided by using the /o 'compile once' regex modifier:
if ($volume =~ /$vol_to_parse/o) {
However, the preferred method with modern Perl is to compile a regex object with the qr operator.
With such an object, you never have to worry about re-compilation unless you really need to do it.
my $rx_vol_to_parse = qr{ \Q$vol_to_parse\E }xms;
if ($volume =~ $rx_vol_to_parse) {
In addition (and probably more importantly), if you use a regex object you don't have to worry about differences in interpolation between single- and double-quoted strings and in regexes, and regex metacharacters. For instance, consider the difference between the behavior of
my $rx = 'x\dy';
and
my $rx = "x\dy";
in the command-line example given above.
As mentioned above, the difference between the two approaches (i.e., regex object vs. naked string) is probably not significant in this particular situation, but it's always best to try to develop good programming habits right from the beginning.
In reply to Re^2: Parsing a file line by line until a certain indice in array
by AnomalousMonk
in thread Parsing a file line by line until a certain indice in array
by sluggo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |