Reputation: 19
p = Popen(our_cmd, shell=True, stdout=PIPE, stderr=PIPE)
output = p.communicate()[0]
split = output.strip('\n\t\r').split("\n")
I want to execute this command which is in string our_cmd
what I have tried is this
my @output = `$our_cmd`; ## here command is executing
my @split = grep(s/\s*$//g, @output); ## the format and putting in new array
@split = split("\n", @split);
My command is executing but not taking input properly. I need output in array in format as in Python code.
Upvotes: 0
Views: 1249
Reputation: 53498
I think you're misunderstanding a couple of perl concepts here. For example - you're split
ing an array - which doesn't make a lot of sense, because split
turns a string into an array, based on a delimiter.
Likewise grep
- that's quite an unusual use of grep
because you've got a search and replace pattern embedded - usually grep
is for filtering based on some boolean expression. (I suspect it works like that, but I'm not entirely sure if your replacement pattern returns true/false, which'll do odd things in a grep
context).
So how about instead:
my @output = `$our_command`;
chomp @output; #removes linefeeds from each element.
for ( @output ) { s/[\t\r]//g; }; #removes linefeeds and carriage returns
This will put into @output
one element per line (including linefeed) and then remove any \t
or \r
in there. If you don't want the linefeed, as Borodin says - chomp @output;
will deal with that.
As mentioned in comments - this may not exactly reproduce what strip
is doing, and the strip
operation may be irrelevant in perl.
Testing your grep:
my @test = ( "test aaa bbb", "mooo", " aaa Moo MMOoo", "no thing in it" );
print join ("\n", grep { s/aaa//g } @test );
This does do the search and replace on $_
(each line of the grep
), but the replace expression does return a 'true/false' - meaning you effectively discard elements that don't contain the pattern at all.
Upvotes: 0
Reputation: 126742
As far as I can tell from your question, all you need is
my @split = `$our_cmd`;
chomp @split;
Upvotes: 2