in reply to regex matching with $1
You also have a bit more escaping than necessary. Try this: $line =~ s/^\$mypic\[0] = "(\w{3})"$/$1/g;
FWIW #1: This is a good example of the problem with using a regex in this way. You may have been thinking that your regex was doing something magically strange to spit back the whole line. In fact it simply failed. So when you do this for the purpose of retreiving a value you almost always want to do something like:
If that looks like too much code and you remember that a regex with parentheses returns those saved values when it is in a list context, you can do this:my $newval; if ($line =~ /^\$mypic\[0] = "(\w{3})"$/) { $newval = $1; } else { # handle failure to get essential value }
For comment on this shorter regex, read on...my $newval; unless ( ($newval) = $line =~ /(\w{3})"$/ ) { # handle failure to get essential value }
FWIW #2: Your question may be more of an exercise than a practical application. But to the extent that this is for some real and specific need, I tend to keep my regexen to the minimum to do the job and try not to get into the trap of matching the entire data string if that is not needed for filtering purposes.
In this case something along the lines of: /(\w{3})"$/ seems to do what you need (within the bounds of this limited example). There are always anomalies that crop up in the data and the more I try to match everything, the more likely it is that the regex could fail for unforeseen reasons.
The notable exception to this habit is when the task is security or access related. Then I get very picky about what I let through.
This may not apply to your present purpose, but it is something that struck me immediately about your longer regex.
HTH, David
|
|---|