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

I have a piece of code that takes the output from a ssh command and puts it into an array. I could put it into a sting also and for this case I use both an array and a string. After I capture the output, I split the array or string on a \n and put the output of this into an array or another string. Next, run a foreach on the array or string and find the lines I need. There has to be a better way, if someone could give me some suggestions, I would appreciate it.

### start of code where I capture the command output $exp->send("show port\n"); $exp->expect(15, [ '# ', sub { my $self = shift; @port = $self->exp_before; }], ); foreach my $line (@port) { my @PORTS = split('\n', $line); foreach my $str (@PORTS){ if ($str =~ /^\d/) { $PORT_NO = (split /\s+/, $str) [0]; $exp->send("show port $PORT_NO detail\n"); $exp->expect(15, [ '# ', sub { my $self = shift; ### Here I use a string to cature the output $output_str = $self->exp_before; }], ); foreach my $string (split('\n', $output_str)){ chomp $string; if ($string =~ /Part Number/) { $model = (split /\s+/, $string) [3]; print "Node: $NODE_NAME,Port: $PORT_NO,Part: $mo +del\n"; } } } } }

Replies are listed 'Best First'.
Re: array and string split
by Anonymous Monk on Jan 27, 2015 at 09:56 UTC
    It seems to me you're asking how to simplify these lines:
    foreach my $line (@port) { my @PORTS = split('\n', $line); foreach my $str (@PORTS){ ... } } }
    Perhaps something like this:
    for my $str ( map { split /\n/ } @port ) { ... }

      Perfect! Thank you!

Re: array and string split
by Anonymous Monk on Jan 27, 2015 at 00:08 UTC

    To assist you better, could you show some example output of the two commands show port and show port $PORT_NO detail that you are trying to parse?* Also, I see you're splitting on '\n', which is a literal backslash followed by a lower case n, is that intentional? If you meant to split on a line break, you should use "\n" (in double quotes, because those interpolate, single quotes don't).

    * Perhaps the output of use Data::Dumper; $Data::Dumper::Useqq=1; print Dumper(\@port); and in the loop print Dumper($output_str);

      I should have mentioned, my approach works very well, just wanted to see if there is a better method.

        There might be, maybe with a regex, but we'd still have to see the string the regex would be operating on...

        On the other hand, if it works well (which usually also means it's well tested and the performance is acceptable), don't touch a running system :-)