Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Pattern matching in perl [short-circuit and declared vs. defined]

by kcott (Archbishop)
on Jun 30, 2022 at 18:30 UTC ( #11145206=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11145206]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2022-08-10 16:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?