12

I want to get the output of a command into an array — like this:

my @output = `$cmd`;

but it seems that the output from the command does not go into the @output array.

Any idea where it does go?

2
  • 6
    Are you sure your command writes to STDOUT? If it writes to STDERR the backticks won't capture this without appending 2>&1 to your call. Commented Jun 5, 2012 at 11:14
  • 3
    How are you determining that the output does not go into the array? Commented Jun 5, 2012 at 11:19

3 Answers 3

17

This simple script works for me:

#!/usr/bin/env perl
use strict;
use warnings;

my $cmd = "ls";    
my @output = `$cmd`;    
chomp @output;

foreach my $line (@output)
{
    print "<<$line>>\n";
}

It produced the output (except for the triple dots):

$ perl xx.pl
<<args>>
<<args.c>>
<<args.dSYM>>
<<atob.c>>
<<bp.pl>>
...
<<schwartz.pl>>
<<timer.c>>
<<timer.h>>
<<utf8reader.c>>
<<xx.pl>>
$

The output of command is split on line boundaries (by default, in list context). The chomp deletes the newlines in the array elements.

Sign up to request clarification or add additional context in comments.

1 Comment

Then you may need to identify your command to us more clearly. I showed the assignment to $cmd; you've not shown what is in the command you're executing. Have you tried using ls or pwd or echo Hello World as the command to see whether you get something useful back? You've also not shown how you're processing the array.
6

The (standard) output does go to that array:

david@cyberman:listing # cat > demo.pl
#!/usr/bin/perl
use strict;
use warnings;
use v5.14;
use Data::Dump qw/ddx/;

my @output = `ls -lh`;
ddx \@output;
david@cyberman:listing # touch a b c d
david@cyberman:listing # perl demo.pl
# demo.pl:8: [
#   "total 8\n",
#   "-rw-r--r--  1 david  staff     0B  5 Jun 12:15 a\n",
#   "-rw-r--r--  1 david  staff     0B  5 Jun 12:15 b\n",
#   "-rw-r--r--  1 david  staff     0B  5 Jun 12:15 c\n",
#   "-rw-r--r--  1 david  staff     0B  5 Jun 12:15 d\n",
#   "-rw-r--r--  1 david  staff   115B  5 Jun 12:15 demo.pl\n",
# ]

Comments

2

Enable automatic error checks:

require IPC::System::Simple;
use autodie qw(:all);
⋮
my @output = `$cmd`;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.