Match regex and assign results in single line of code

后端 未结 9 1918
后悔当初
后悔当初 2021-02-02 06:45

I want to be able to do a regex match on a variable and assign the results to the variable itself. What is the best way to do it?

I want to essentially combine lines 2 a

相关标签:
9条回答
  • 2021-02-02 07:30

    Well, you could say

    my $variable;
    ($variable) = ($variable = "find something soon") =~ /(find something).*/;
    

    or

    (my $variable = "find something soon") =~ s/^.*?(find something).*/$1/;
    
    0 讨论(0)
  • 2021-02-02 07:32

    Why do you want it to be shorter? Does is really matter?

    $variable = $1 if $variable =~ /(find something).*/;
    

    If you are worried about the variable name or doing this repeatedly, wrap the thing in a subroutine and forget about it:

     some_sub( $variable, qr/pattern/ );
     sub some_sub { $_[0] = $1 if eval { $_[0] =~ m/$_[1]/ }; $1 };
    

    However you implement it, the point of the subroutine is to make it reuseable so you give a particular set of lines a short name that stands in their place.


    Several other answers mention a destructive substitution:

    ( my $new = $variable ) =~ s/pattern/replacement/;
    

    I tend to keep the original data around, and Perl v5.14 has an /r flag that leaves the original alone and returns a new string with the replacement (instead of the count of replacements):

    my $match = $variable =~ s/pattern/replacement/r;
    
    0 讨论(0)
  • 2021-02-02 07:32

    From Perl Cookbook 2nd ed 6.1 Copying and Substituting Simultaneously

    $dst = $src;
    $dst =~ s/this/that/;
    

    becomes

    ($dst = $src) =~ s/this/that/;
    

    I just assumed everyone did it this way, amazed that no one gave this answer.

    0 讨论(0)
提交回复
热议问题