【问题标题】:Breaking up qx/ return in Perl在 Perl 中分解 qx/return
【发布时间】:2017-08-03 20:32:31
【问题描述】:

我有一个 Ubuntu 16.04.1 服务器,我乱用它。目前我正在使用它来监控我的互联网速度和连接。

我已经编写了一个脚本并使用 Perl 和 crontab 将其自动化,但现在我想清理我的日志文件。

以下是执行 Perl 脚本时写入日志文件的内容:

Time: 12:40:01
Retrieving speedtest.net configuration...
Testing from TWC (now Spectrum) (123.45.67.890)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by Fibrant (Salisbury, NC) [60.95 km]: 51.184 ms
Testing download     speed................................................................................
Download: 37.76 Mbit/s
Testing upload speed....................................................................................................
Upload: 11.56 Mbit/s

我希望得到以下输出:

Download: 37.76 Mbit/s
Upload: 11.56 Mbit/s

我当前的 Perl 脚本如下所示:

    use strict;
    use warnings;

    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime( time );
    my $nice_timestamp = sprintf( "%04d%02d%02d",   $year + 1900, $mon + 1, $mday );
    my $timer          = sprintf( "%02d:%02d:%02d", $hour,        $min,     $sec );
    my $filename = "/home/user/DailyLogs/InternetLog$nice_timestamp";

    open( my $fh, '>>', $filename ) or die "Could not open file '$filename' $!";

    my $output = qx"/home/user/.local/bin/speedtest-cli";

    print $fh "Time: ";
    print $fh $timer;
    print $fh "\n";
    print $fh $output;
    print $fh "\n\n";

    close $fh;

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: perl command-line scripting


    【解决方案1】:

    您可以使用grep 过滤qx 输出:

    my @output = grep {/^(Up|Down)load:/} qx"/home/user/.local/bin/speedtest-cli";
    print $fh $_ for @output;
    

    附带说明,您可以使用 POSIX 简化您的 $timer 代码:

    use POSIX qw(strftime);
    my @localtime = localtime;
    my $nice_timestamp = strftime('%Y%m%d',   @localtime);
    my $timer          = strftime('%H:%M:%S', @localtime);
    

    【讨论】:

      【解决方案2】:

      如果您将结果分配给数组,则反引号(qx 运算符)会将输出分成几行。您可以使用grep 选择您想查看的线路

      我也会使用 Time::Piece 生成时间和日期字符串的模块

      代码如下所示

      use strict;
      use warnings 'all';
      
      use Time::Piece;
      
      my $now = localtime;
      $now->date_separator('');
      my $nice_timestamp = $now->ymd; # Generates YYYYMMDD
      
      my $filename = "/home/user/DailyLogs/InternetLog$nice_timestamp";
      
      open my $fh, '>>', $filename or die qq{Unable to open file "$filename" for appending: $!};
      
      my @output = qx</home/user/.local/bin/speedtest-cli>;
      
      my $timer = $now->hms; # Generates HH:MM:SS
      
      print $fh "Time: $timer\n";
      print $fh for grep /^(?:Down|Up)load/, @output;
      print $fh "\n\n";
      
      close $fh;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-31
        • 2012-08-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多