http://qs321.pair.com?node_id=1057295


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?