How can I extract the matches from the Perl match operator into variables?

前端 未结 6 1007
无人及你
无人及你 2020-12-29 08:09

If I have a match operator, how do I save the parts of the strings captured in the parentheses in variables instead of using $1, $2, and so on?

6条回答
  •  孤城傲影
    2020-12-29 08:30

    Usually you also want to do a test to make sure the input string matches your regular expression. That way you can also handle error cases.

    To extract something interesting you also need to have some way to anchor the bit you're interested in extracting.

    So, with your example, this will first make sure the input string matches our expression, and then extract the bit between the two 'boring' bits:

    $input = "boring interesting boring";
    if($input =~ m/boring (.*) boring/) {
        print "The interesting bit is $1\n";
    }
    else {
        print "Input not correctly formatted\n";
    }
    

提交回复
热议问题