Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Create a map from multiple ping output

by kcott (Archbishop)
on Sep 21, 2020 at 12:12 UTC ( [id://11121997]=note: print w/replies, xml ) Need Help??


in reply to Create a map from multiple ping output

G'day Leo,

"... there is probably a better way to do it."

There would be many ways to this. The unqualified term "better" is highly subjective: if it relates to efficiency, then Benchmark possible solutions; if it relates to other criteria, you'll need to tell us about that or assess for yourself.

Here's one way you could do it:

$ perl -e ' use strict; use warnings; use autodie ":all"; my @hosts = qw{8.8.8.8 8.8.4.4}; my $command = join ";", map "ping -c3 ".$_, @hosts; my $result = qx{$command}; my $re = qr{(?s:^(\S+).+?(\S+)\s+ms\s*$)}; my $fmt = "%s min:%s avg:%s max:%s mdev:%s\n"; open my $mh, "<", \$result; { local $/ = "PING "; while (<$mh>) { chomp; next unless /$re/; printf $fmt, $1, split /\//, $2; } } ' 8.8.8.8 min:16.929 avg:17.290 max:17.585 mdev:0.272 8.8.4.4 min:15.392 avg:15.856 max:16.284 mdev:0.365

Notes:

  • Use of the strict and warnings pragmata. Highly recommended; compulsory in my opinion.
  • A more succinct method for creating the command.
  • Capturing the result as a single string which is subsequently processed by Opening a filehandle into an in-memory scalar.
  • A simplified regex for use on an entire ping result. The four (min/avg/max/mdev) values are captured as a single entity and later split when the individual values are required.
  • A format for standardised report output; used later by printf.
  • Reading individual ping results by manipulating $/ (see "perlvar: Variables related to filehandles").

I've shown a number of different ways to do various things. Pick and choose the bits you want; or, use as is, if you like all of it.

— Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11121997]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (1)
As of 2024-04-24 14:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found