Reading output from command into Perl array

前端 未结 3 1094
无人及你
无人及你 2020-12-20 13:26

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

3条回答
  •  眼角桃花
    2020-12-20 13:53

    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
    <>
    <>
    <>
    <>
    <>
    ...
    <>
    <>
    <>
    <>
    <>
    $
    

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

提交回复
热议问题