in reply to condense conditional

Semi-tested :)

#!/usr/bin/perl # https://perlmonks.org/?node_id=1222210 use strict; use warnings; my $devstats; readfile("/sys/class/net/dsl/statistics/rx_bytes"); readfile("/sys/class/net/dsl/mtu"); readfile("/sys/class/net/tybalt/mtu"); readfile("/sys/class/net/tybalt/statistics/rx_bytes"); readfile("/sys/class/net/dsl/queues/tx-0/byte_queue_limits/inflight"); use Data::Dumper; print Dumper $devstats; exit(0); sub readfile { my $file = shift; my @data = split("/", $file); my $nic = $data[4]; open(FIFO, "< $file") or die "$! opening $file"; my $value = <FIFO>; if (defined($value)) { chomp($value); my $hashref = \$devstats->{$nic}; $hashref = \$$hashref->{$_} for @data[5 .. $#data]; $$hashref = $value; } close(FIFO); }

Outputs (on my system):

$VAR1 = { 'tybalt' => { 'statistics' => { 'rx_bytes' => '26296' }, 'mtu' => '1500' }, 'dsl' => { 'mtu' => '1500', 'queues' => { 'tx-0' => { 'byte_queue_limits' => +{ + 'inflight' => '0' +} } }, 'statistics' => { 'rx_bytes' => '51353977825' } } };

Replies are listed 'Best First'.
Re^2: condense conditional
by ikegami (Patriarch) on Sep 12, 2018 at 15:35 UTC
    my $hashref = \$devstats->{$nic}; $hashref = \$$hashref->{$_} for @data[5..$#data]; $$hashref = $value;
    should be
    my $scalarref = \$devstats->{$nic}; $scalarref = \$$scalarref->{$_} for @data[5..$#data]; $$scalarref = $value;
    This can be simplified to
    my $scalarref = \$devstats; $scalarref = \$$scalarref->{$_} for $nic, @data[5..$#data]; $$scalarref = $value;
    or
    my $scalarref = \$devstats; $scalarref = \$$scalarref->{$_} for @data[4..$#data]; $$scalarref = $value;
    This can be replaced with
    sub dive_val :lvalue { my $p = \shift; $p = \$$p->{$_} for @_; $p } dive_val($devstats, @data[4..$#data]) = $value;
    or
    use Data::Diver qw( DiveVal ); DiveVal($devstats //= {}, map \$_, @data[4..$#data]) = $value;

    How these work is explained here.

Re^2: condense conditional
by mdidomenico (Initiate) on Sep 12, 2018 at 15:13 UTC
    This one works for me. Thanks!