简体   繁体   中英

Perl, Assign to variable from regex match

I am relatively new to perl and there is an example snippet of code in check_ilo2_health.pl in which there is a piece of syntax that I do not understand how or why it works. The code snippet is parsing SSL client data, in this case XML, line by line.

if ( $line =~ m/MESSAGE='/) {
   my ($msg) = ( $line =~ m/MESSAGE='(.*)'/);  #<---- HERE

   if ( $msg !~ m/No error/ ) {
      if ( $msg =~ m/Syntax error/ ) {  #...etc

An example of the XML in question:

<RESPONSE
    STATUS="0x0000"
    MESSAGE='No error'
 />

So in this case the if statement takes the MESSAGE line of the XML sample. I understand that my ($msg) treats the variable as a sort of list and I understand how the regular expressions match; however, what I do not understand is the syntax such that $msg is assigned to No error . The perl seems to be playing around with parenthesis syntax and such for this to work. While it works I would like to know how it works. Any assistance would be appreciated.

See Perlretut, Extracting-matches :

... in scalar context, $time =~ /(\\d\\d):(\\d\\d):(\\d\\d)/ returns a true or false value. In list context, however, it returns the list of matched values ($1,$2,$3)

So, in

($msg) = ( $line =~ m/MESSAGE='(.*)'/);

( $line =~ m/MESSAGE='(.*)'/) returns a list of the matches by the capturing groups. You have one capturing group, so the content of that is then stored in ($msg).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM