in reply to Assigning a varable inside of (?{})

You can just use the named captures $1 and $2 to store the values (also note the warning in perlre about (?{ code }) being highly experimental).. also, no need for string references here.
use strict; use warnings; while (<DATA>) { next unless /\S/; my ( $sunrise, $sunset ) = get_time($_); next unless $sunrise && $sunset; printf "Sunrise is: %s Sunset is: %s\n", $sunrise, $sunset; } sub get_time { my $string = shift; return unless $string =~ /sunrise:\s+(\d+:\d+)\s+sunset:\s+(\d+:\d+) +/; return ( $1, $2 ); } __DATA__ Aberdeen, Scotland 57 9 N 2 9 W sunrise: 03:12 sunset: 21:08 Adelaide, Australia 34 55 S 138 36 E sunrise: 06:52 sunset: 16:41
But where the undef was coming from was a blank line in <DATA> ... so the match failed, so $sunrise/$sunset where undef. Just a quick check for a valid string/success on the match resolves it.

Replies are listed 'Best First'.
Re^2: Assigning a varable inside of (?{})
by davido (Cardinal) on May 03, 2006 at 16:18 UTC

    But where the unief was coming from was a blank line in <DATA> ... so the match failed...

    No it didn't. Place a "or die qq/failed\n/;" after the regexp and you'll see. While the OP certanly wouldn't ever know if it did or didn't fail (because he doesn't check), when I checked, it's not failing. The real problem is a scoping issue related to when regexes are compiled.

    Update:
    I do want to congratulate you on zeroing in on the optimal solution, however. I see no good reason to be relying on (?{...}) and $^N, with their inherent difficulties, just to emulate what $1 and $2 do automatically, and without the complexity.


    Dave

Re^2: Assigning a varable inside of (?{})
by monsterzero (Monk) on May 03, 2006 at 16:32 UTC
    Hello,

    I don't think that is the problem. If you look at the error it is in line 2. If what you say is true it would have said line 3. I believe (from the other answer) it is a scopeing issue? Anyway thanks for the reply.