Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm using the following code:
#!/usr/bin/perl use strict; use warnings; while (<DATA>) { my $one = $1 if /^\{\w+\s+\d+\}([^\s\t]+)/; my $two = $1 if /^\{\w+\s+\d+\}\s+(.*)/; print "ONE: $one\n"; print "TWO: $two\n"; } __DATA__ {STRING 4} 123.122.124.125 some text here
My desired result is:
ONE: {STRING 4} TWO: 123.122.124.125 some text here
Any ideas what I'm doing wrong. This should work!

Replies are listed 'Best First'.
Re: Silly RegEx problem
by cLive ;-) (Prior) on Feb 19, 2004 at 18:51 UTC
    You might also want to put it into one regex, depending on context:
    while (<DATA>) { my ($one,$two); if ( /^\({\w+\s+\d+\})\s+(.*)/ ) { $one = $1; $two = $2; } print "ONE: $one\n"; print "TWO: $two\n"; }

    .02

    cLive ;-)

Re: Silly RegEx problem
by Wonko the sane (Curate) on Feb 19, 2004 at 18:44 UTC
    Doesn't look like you are capturing the part you are trying to print. No capturing parens.
    The first regex, also does not match your input.

    This would give you what you say you want.
    my $one = $1 if /^(\{\w+\s+\d+\})/;

    Wonko
Re: Silly RegEx problem
by ysth (Canon) on Feb 19, 2004 at 21:14 UTC
    Do not  say my $foo if bar; $foo will not be properly initialized to undef if bar is false.   As the FM says, "Here be dragons."   (And Abigail, I'd expect you to have seen just how often this bites people here at perlmonks.)
Re: Silly RegEx problem
by dragonchild (Archbishop) on Feb 19, 2004 at 18:47 UTC
    #!/usr/bin/perl use strict; use warnings; while (defined( $_ = <DATA>)) { my $one = $1 if s/^(\{\w+\s+\d+\}) //; my $two = $1 if s/^(.*)//; print "ONE: $one\n"; print "TWO: $two\n"; } __DATA__ {STRING 4} 123.122.124.125 some text here

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.