actum has asked for the wisdom of the Perl Monks concerning the following question:

Hy I have this pice of code:
@inv0 = split(/\n/,qx'/usr/sbin/iptables -L DOWN0 -v -n -x | awk \'{ +print $8" - "$2}\' | egrep \'^192\''); @outv0 = split(/\n/,qx'/usr/sbin/iptables -L UP0 -v -n -x | awk \'{pri +nt $7" - "$2}\' | egrep \'^192\''); @inv1 = split(/\n/,qx'/usr/sbin/iptables -L DOWN1 -v -n -x | awk \'{p +rint $8" - "$2}\' | egrep \'^192\''); @outv1 = split(/\n/,qx'/usr/sbin/iptables -L UP1 -v -n -x | awk \'{pri +nt $7" - "$2}\' | egrep \'^192\''); @inv2 = split(/\n/,qx'/usr/sbin/iptables -L DOWN2 -v -n -x | awk \'{p +rint $8" - "$2}\' | egrep \'^192\''); @outv2 = split(/\n/,qx'/usr/sbin/iptables -L UP2 -v -n -x | awk \'{pri +nt $7" - "$2}\' | egrep \'^192\'');
so how can i make this in an for structure to avoid repetition? I have tried with arrays in arrays but no succes. Second I do not know how to expand an variable in an qx section.

Replies are listed 'Best First'.
Re: expanding variables in variables
by revdiablo (Prior) on May 22, 2006 at 16:18 UTC

    First, I'd like to note that the guts of your pipeline can be replaced by pure Perl code. All you really need to call is the iptables command. That said, the reason you're not getting Perl variables interpolated into your qx is because you're using single quotes as the delimiter. Try this instead:

    for (0 .. 2) { my $output = qx{echo '\$_ is $_'}; print $output; }

    As for moving that into a better data structure, my first thought is an array of arrays, but the exact structure you'll want really depends on what you want to do with it:

    my @things; for (0 .. 2) { my @inv = ...; my @outv = ...; push @things, [ \@inv, \@outv ]; }
Re: expanding variables in variables
by QM (Parson) on May 22, 2006 at 16:57 UTC
    Can't you drop the split with qx?
    In scalar context, it comes back as a single (potentially multi-line) string, or undef if the command failed. In list context, returns a list of lines (however you've defined lines with $/ or $INPUT_RECORD_SEPARATOR), or an empty list if the command failed.

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      Yup, but then the \n is still at the end of each line then, so you need to chop or chomp the array to get the same result.

                      - Ant
                      - Some of my best work - (1 2 3)