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";

In reply to Re: using Backtick inside perl gives different output by ig
in thread using Backtick inside perl gives different output by kaka_2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.