[Melbourne-pm] Regexps - how does the lexical scope of capture buffers work? (Was: Regexp: What's the right way to do this?)

Shlomi Fish shlomif at shlomifish.org
Wed Oct 17 05:49:44 PDT 2012


Hi Nathan,

On Wed, 17 Oct 2012 23:24:03 +1100
Nathan Bailey <nathan.bailey at monash.edu> wrote:

> Oops, accidentally only replied to Shlomi.
> 
> With the input file:
>    8:10 -
>    9:15
> 
> a.pl products:
> 8:10 - 9:15
> 
> but b.pl produces:
> Why is start_time undefined now? at b.pl line 8, <> line 2.
> - 9:15
> 
> I presume it fails because the regexp fails, returning undef which is
> then assigned to $start_time, rather than failing and skipping the
> assignment.

Well, with

use strict;
my ($start_time, $finish_time);
while (<>) {
   if (($start_time) = m#^\s*(\d+:\d+) -#) {
      ;
   } elsif (($finish_time) = m#^\s*(\d+:\d+)#) {
      ;
      warn "Why is start_time undefined now?" if !defined $start_time;
      print "$start_time - $finish_time\n";
   }
}

if the clause in the "if" line fails, then the list ($start_time) will be assigned
from the empty list, causing $start_time to become undef. What you want is:

if (my ($new_start_time) = m#^\s*(\d+:\d+) -#) {
	$start_time = $new_start_time;
}

Untested.

Regards,

	Shlomi Fish


-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
UNIX Fortune Cookies - http://www.shlomifish.org/humour/fortunes/

Chuck Norris doesn’t commit changes, the changes commit for him.
    — Araujo

Please reply to list if it's a mailing list post - http://shlom.in/reply .


More information about the Melbourne-pm mailing list