It may have nothing to do with scoping at all. Basic rule is that a my variable is visible to everything in the block in which it's declared, so as long as your "if" is within the while loop, $date will be visible. I'd point a finger (tentatively) at

/(\w{3}\s+\w{3}\s+\d{1,2}/; my $date = $1;

For two reasons: one is that it's not well-formed. You should be getting an error on that (There's no closing paren). So if this is cut-n-paste, that's a problem right there. Second problem is that (assuming there is a closing paren in the actual code) if that regex doesn't match, $1 won't be set, and it's no surprise that you get nothing when you print out the value of $date.

You *are* running with -w and strict on, aren't you? The present case is a VERY good example of why you should; if $date doesn't get set and you try to print it, -w will tell you it's uninitialized. And if $date has gone out of scope, strict will complain about it not being declared. So: use -w and strict : really.

The fix, assuming you want to ignore lines that don't match your date-finding pattern:

#!/usr/bin/perl -w use strict; # stuff # (in while loop) while (<my_file>) { next unless my ($date) =~ /(\w{3}\s+\w{3}\s+\d{1,2})/; # stuff if ($foo) { print "Date is $date\n"; } # more stuff }

HTH!


In reply to Re: Scoping Variables by arturo
in thread Scoping Variables by stuffy

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.