Can this be done on one line?

I am extracting the MAC address so

my @tmp = split / /, "domain (123.123.123.123) at 00:11:22:33:44:55 [ether] on eth0"; my $vip = $tmp[3]; 

but can this be done without using a temporary variable?

+6
source share
4 answers

Yes, he can:

 my $vip = (split / /, "domain (123.123.123.123) at 00:11:22:33:44:55 [ether] on eth0")[3]; 
+15
source

Yes it is possible.

 my (undef, undef, undef, $vip) = split / /, "..."; 
+12
source

I would recommend this approach, which searches for the โ€œcorrectโ€ MAC address at word boundaries in a haystack. If the MAC address moves in the line, it will still work, and if $vip not determined after this statement, the MAC address is not found. Let me know if I can clarify anything.

 my ($vip) = "..." =~ /\b((?:[0-9A-Fa-f]{1,2}[:-]){5}[0-9A-Fa-f]{1,2})\b/; 
+6
source

You can use grep . This will capture the first field matching the regular expression. Please note: if you specifically do not want multiple spaces leading to empty fields, you should use ' ' , not / / .

 my ($vip) = grep /^[0-9:]+$/, split ' ', "..."; 
+4
source

Source: https://habr.com/ru/post/900711/


All Articles