in reply to Scoping Variables

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!

Replies are listed 'Best First'.
Re: Re: Scoping Variables
by stuffy (Monk) on May 18, 2001 at 08:08 UTC
    while (<NEW_HIST>){ /^(\w{3}\s+\w{3}\s+\d{1,2})/; my $pass_down_date = $1 if (/$tool/){ print "$pass_down_date"; $print_checker = 1; } if (/$stop/){ $print_checker = 0; } if ($print_checker){ print "$_ <br>\n"; } }

    this is the actual code in the loop. $pass_down_date is being matched, it will print outside of any of the if loops. If I try to print it out inside any of the if loops, it comes back with what I believe is an empty string.
    by the way, strict and -w are on. :)

    Stuffy