in reply to I'm reading a book! It's given me more questons!
Dropping the () around $what will make it compile, but that really changes what the code is saying.my $what = "fred|barney"; ... if ($_ =~ ($what){3}) { ... }
is going to try to find the value in %what that is assosciated with the key '3' and use that as a regex. Unless you have some %what hash, this will be undef and will be intrepreted asif ($_ =~ $what{3}) { ... }
which will match anything, including nothing. Essentially, that's justif ($_ =~ //) { ... }
and you most likely do not want that.if (1) { ... }
This
probably does the closest to what you want (match three occurrences of 'fred' or 'barney' in any order. This works because =~ treats whatever it finds on the right hand side as a RE (regular expression).my $what = "(fred|barney){3}"; ... if ($_ =~ $what) { ... }
You could get the same behavior from either of your examples by using the m// operator (the 'm' can be omited if you are using slashes as the delimiter).
If you do this, then you can eliminate the '$_ =~' as it is redundant:if ($_ =~ /($what){3}/) { ... } .... if ($_ =~ /$what/) { ... }
if (/($what){3}/) { ... } ... if (/$what/) { ... }
|
|---|