Using match variable $1 for 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/13 21:53 UTC
Read the original article Hit count: 306

Filed under:

What is the cleanest way of picking up a match variable form a subsitution 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 be cleanest way of doing it.

© Stack Overflow or respective owner

Related posts about perl