Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the match variable $1 following a substitution in Perl?

Tags:

perl

What is the cleanest way of picking up a match variable from a substitution in Perl I sometimes find myself writing

    s/(something)// ;
    my $x = $1 ;

then I realise that if the s/ / / fails $1 might be carrying over a value from a previous match. So I try

    my  $x = 'defaultvalue' ;
    if ( s/(something)// )
    {
     $x = $1 ;
    }

Is this the cleanest way of doing it?

like image 610
justintime Avatar asked Apr 13 '10 21:04

justintime


People also ask

What does $1 do in Perl?

The $number variables contain the parts of the string that matched the capture groups ( ... ) in the pattern for your last regex match if the match was successful. $1 equals the text " brown ".

How do I match a variable in Perl?

Perl makes it easy for you to extract parts of the string that match by using parentheses () around any data in the regular expression. For each set of capturing parentheses, Perl populates the matches into the special variables $1 , $2 , $3 and so on. Perl populates those special only when the matches succeed.

What does $? Mean in Perl?

$? is the error code of the child process (perform_task.sh). In the case of your script the return code is shifted eight bits to the right and the result compared with 0. This means the run is considered a failure only if the returned code is > than 255.

What does =~ do in Perl?

The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match. In our case, World matches the second word in "Hello World" , so the expression is true.


2 Answers

TMTOWTDI.

The idiomatic Perl usually seen might be somthing like:

my $x='defaultvalue';

$x=$1 if (s/(something)//) ;
like image 91
dawg Avatar answered Sep 28 '22 00:09

dawg


As others have pointed out, TIMTOWTDI.

I'd personnally wrap it up as a single expression, so as not to distract too much from the point:

my $x = s/(something)// ? $1 : 'defaultvalue';
like image 21
JB. Avatar answered Sep 27 '22 22:09

JB.