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


In reply to Re: Pattern matching in perl [short-circuit and declared vs. defined] by kcott
in thread Pattern matching in perl by noviceuser

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.