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

Posted by justintime on Stack Overflow See other posts from Stack Overflow or by justintime
Published on 2010-04-13T21:46:38Z Indexed on 2010/04/14 15:43 UTC
Read the original article Hit count: 137

Filed under:

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

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

then I realize 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?

© Stack Overflow or respective owner

Related posts about perl