Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 873
Burns Avatar asked Feb 05 '13 19:02

Burns


1 Answers

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).

like image 74
stema Avatar answered Sep 22 '22 13:09

stema