in reply to Re^2: undef a variable for a loop
in thread undef a variable for a loop

Based on this additional information, you probably mean something like this:

foreach $exch(@exch) { undef($su_adapter); undef($su_date); for($i=0; $i<=$#completefile; $i++) { if($completefile[$i]=~ m/^.+\\(.+)_.+\..+?:(.+?)\s-\s(.+?)\s.+ +?\/$exch\s\|.+::(.*Up)\(\)/) { $su_adapter=$1; $su_date=$2; } } print $su_adapter, $su_date; }

Note that there are a bunch of easy modifications (as shown in ikegami's post) that can simplify your code and reduce its predilection for bugs.

Replies are listed 'Best First'.
Re^4: undef a variable for a loop
by ikegami (Patriarch) on May 15, 2009 at 19:00 UTC
    No. Four problems with your solution:
    • undef($var); is less efficient than $var = undef;.
    • The print still needs to be in an if in case there was no match.
    • Using undef at all is useless (because of previous point).
    • That doesn't find the last match of each file. It only finds the last match of one file.
      There are a host of problems with my solution. However it solves the posted issue (reporting cached hits) as I understand the snippet. If we assume that @completefile is a file slurp (i.e. @completefile = <$fh>), then this loop will output the last $exch match in the file. If I misunderstand the spec and each line of @completefile represents a file slurp (i.e. local $/; push @completefile,<$fh>), then a solution could be obtained using a g modifier (and likely an m to boot) on the regex and a while loop:

      foreach $exch(@exch) { for($i=0; $i<=$#completefile; $i++) { $su_adapter = undef; $su_date = undef; while($completefile[$i]=~ m/^.+\\(.+)_.+\..+?:(.+?)\s-\s(.+?)\ +s.+?\/$exch\s\|.+::(.*Up)\(\)/g) { $su_adapter=$1; $su_date=$2; } print $su_adapter, $su_date; } }

      I disagree with your point about printing since I generally care as much about a failed match as a successful match, and as long as the OP clearly isn't using warnings, printing undefs (with formatting like perhaps a newline) is appropriate. In any case, were I to have coded this, it would look a lot more like

      foreach my $exch (@exch) { my ($su_adapter, $su_date); foreach (reverse @completefile) { last if ($su_adapter, $su_date) = /^.+\\(.+)_.+\..+?:(.+?)\s-\ +s(.+?)\s.+?\/$exch\s\|.+::(.*Up)\(\)/; } if (defined $su_adapter) { print "Last match for $exch: $su_adapter, $su_date\n"; } else { print "No match for $exch\n"; } }

      In the end, much of this is strictly academic, since this the OP never posted enough code to really understand what they intended.

        In your second snippet, you still print the last match of the last file, not the last match of each file.

        I disagree with you point about printing

        Then why did you proceed by putting the print in an if?

        You're right, I apologize, I just updated my post with the script, if anyone can take a look again, i'd appreciate it...