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?
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 ".
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.
$? 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.
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.
TMTOWTDI.
The idiomatic Perl usually seen might be somthing like:
my $x='defaultvalue';
$x=$1 if (s/(something)//) ;
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With