Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: using Backtick inside perl gives different output

by ig (Vicar)
on Oct 07, 2013 at 18:25 UTC ( #1057295=note: print w/replies, xml ) Need Help??


in reply to using Backtick inside perl gives different output

As suggested by Laurent R, you might consider using more Perl and less files and system commands.

If you like terse, you might try something like:

use strict; use warnings; my $cmd = "/usr/sbin/ntpq -p"; my $offset = (split(/\s+/, (grep(/^\*/, `$cmd`))[0]))[8]; print "$offset\n";

If you find that a bit difficult to read and would prefer several statements with intermediate variables, you might try something like:

use strict; use warnings; my $cmd = "/usr/sbin/ntpq -p"; my @ntpout = `$cmd`; my $current_time_source = (grep(/^\*/, @ntpout))[0]; my $offset = (split(/\s+/, $current_time_source))[8]; print "$offset\n";

You should also think about what will happen if there are errors or unexpected situations. You might change the latter to something like:

use strict; use warnings; my $cmd = "/usr/sbin/ntpq -p"; my @ntpout = `$cmd`; die "$cmd failed with: $^E, $?" unless(@ntpout); my $current_time_source = (grep(/^\*/, @ntpout))[0]; die "Not synchronized" unless($current_time_source); my $offset = (split(/\s+/, $current_time_source))[8]; die "$current_time_source: No offset" unless(defined($offset)); print "$offset\n";

Replies are listed 'Best First'.
Re^2: using Backtick inside perl gives different output
by kaka_2 (Sexton) on Oct 08, 2013 at 17:11 UTC
    This is what i wanted to do but i was spliting @ntpout without getting value for my $current_time_source and i still dont understand why would you do so?

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2020-09-27 14:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (142 votes). Check out past polls.

    Notices?