http://qs1969.pair.com?node_id=11145206


in reply to Pattern matching in perl

G'day noviceuser,

In addition to issues already pointed out, you have a problem with short-circuited logic. Search perlop for "short-circuit": you'll find 9 matches which explain what it is and where it does (or does not) apply.

Also, it may just be a typo; however, as a noviceuser, it occurs to me that you may not be fully across the difference between a variable being declared and defined.

In your code you declare $pattern with 'my $pattern;'. At this point, $pattern has not been assigned a value; i.e. it is undefined.

In the next statement you have an 'if' whose condition is '(defined($pattern) && ...)'. Because 'defined($pattern)' is FALSE, Perl does not bother evaluating the remainder of the condition: it already knows the entire condition is FALSE. This is an example of short-circuiting.

"... but the pattern match is not working."

It's not a case of it not working: it's never evaluated. Whether your regex is correct or not doesn't come into play.

Consider these:

$ perl -E 'my $pattern; say +(defined($pattern)) ? "YES" : "NO"' NO $ perl -E 'my $true = 1; say +(defined($true)) ? "YES" : "NO"' YES $ perl -E 'my $true = 1; my $pattern; say +(defined($pattern) && $true +) ? "YES" : "NO"' NO $ perl -E 'my $true = 1; my $pattern; say +(defined($pattern) || $true +) ? "YES" : "NO"' YES

— Ken