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

Could any one guide me if there is other smart way to merge these three line code to one line, Please!
$line =~ /Id="(.*?)".*?>(.*?)</) my $Rkey_id = $1; my $Rkey_val = $2;
Cheers!!!

Replies are listed 'Best First'.
Re: Regular Expression
by ikegami (Patriarch) on Jun 24, 2009 at 03:26 UTC
    And to add some error checking,
    my ($Rkey_id, $Rkey_val) = $line =~ /Id="(.*?)".*?>(.*?)</ or die("Foo!\n");
Re: Regular Expression
by kennethk (Abbot) on Jun 24, 2009 at 03:16 UTC
    As discussed in Extracting matches, when you use a regular expression in list context, it returns the captured values. Thus:

    my ($Rkey_id, $Rkey_val) = $line =~ /Id="(.*?)".*?>(.*?)</

    Update: extraneous parenthesis in regex fixed - nice catch, AnomalousMonk

      my ($Rkey_id, $Rkey_val) = $line =~ /Id="(.*?)".*?>(.*?)</) above code return correct result but when i try this,
      my $line = "AAA:BBB:CCC"; my $var = $line =~ /.*?:(\w+):.*?$/; print "$var\n";
      If i am just interested in "BBB", above code returning 1 rather than BBB, Could any one guide me why? and how can I achieve this? Please. Cheers
        It is all in the context.

        Your assignment to "my $var" is in a scalar context.

        The result of the regular expression is a single item in a list context.

        You can get the desired result by:

        my ($var) = $line =~ /.*?:(\w+):.*?$/; # Declare $var in a List contex +t.

             Potentia vobiscum ! (Si hoc legere scis nimium eruditionis habes)

Re: Regular Expression
by AnomalousMonk (Archbishop) on Jun 24, 2009 at 03:16 UTC
    >perl -wMstrict -le "my $line = 'Id=\"123\" foo >987<'; my ($Rkey_id, $Rkey_val) = $line =~ /Id=\"(.*?)\".*?>(.*?)</; print $Rkey_id; print $Rkey_val; " 123 987

    Update: see also Set variables from m//.