简体   繁体   中英

Perl regular expression and arguments

The following Perl example is part of long Perl script.

This script takes the results from ifconfig -a and prints the IP address.

Can someone explain how $1 gets the IP address?

And what the regular expression

$RESULTS =~ /addr:(\S+)\s+/

means?

  my $COMMAND = "ifconfig -a | grep inet | grep -v 127.0.0.1 | head -1";
  my $RESULTS = `$COMMAND`;
  chomp $RESULTS;
  #          inet addr:106.13.4.9  Bcast:106.13.4.255  Mask:255.255.255.0
  #          inet 106.13.4.9 netmask ffffff80 broadcast 106.13.4.127


if ( $RESULTS =~ /addr:(\S+)\s+/ ) {
    $IpAddress = $1;
}
elsif ( $RESULTS =~ /inet\s+(\S+)\s+/ ) {
    $IpAddress = $1;
}

print "IpAddress = $IpAddress\n";

If a =~ match expression is true, the special variables $1 , $2 , ... will be the substrings that matched parts of the pattern in parenthesis. $1 matches the first left parenthesis, $2 the second left parenthesis, and so on.

\\S matches any non-whitespace character,
+ match 1 or more times,
\\s matches any whitespace character (space, tab, newline),

So in your regex it matches addr:(any non-whitespace character 1 or more time)matches any whitespace character one or more time . And $1 in capturing the value in parenthesis.

See this question to understand $1 : What does $1 mean in Perl?

=~ is the matches operator in perl and evaluates to true if a string (here $RESULTS ) can be matched with a regular expression (here /addr:(\\S+)\\s+/ )

When a regular expression is matched in perl, variables are automatically assigned:

  • $& holds the part matched by the whole expression
  • $1 holds the part matched by the first capture group (set of parantheses)
  • $2 the part by the second capture group
  • and so on ...

$1 , $2 , $& etc will capture the value the last successful match.

\\S+ matches any and negates \\s (whitespace).

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