How can I store regex captures in an array in Perl?

后端 未结 7 1212
孤城傲影
孤城傲影 2020-12-01 03:38

Is it possible to store all matches for a regular expression into an array?

I know I can use ($1,...,$n) = m/expr/g;, but it seems as though that can on

7条回答
  •  猫巷女王i
    2020-12-01 04:01

    I think this is a self-explanatory example. Note /g modifier in the first regex:

    $string = "one two three four";
    
    @res = $string =~ m/(\w+)/g;
    print Dumper(@res); # @res = ("one", "two", "three", "four")
    
    @res = $string =~ m/(\w+) (\w+)/;
    print Dumper(@res); # @res = ("one", "two")
    

    Remember, you need to make sure the lvalue is in the list context, which means you have to surround scalar values with parenthesis:

    ($one, $two) = $string =~ m/(\w+) (\w+)/;
    

提交回复
热议问题