in reply to Perl: Split/format the output and append it to an array
I have the below code
What is my $stream = streamname; meant to do? "streamname" is a bare word, and without strict it will be interpreted as a literal string. What for?
my $xlink,@xlinkpaths;
This doesn't do what you want. To give my a list, you have to wrap the list in parens:
perl -Mstrict -ce 'my $xlink,@xlinkpaths' Global symbol "@xlinkpaths" requires explicit package name at -e line +1. -e had compilation errors. perl -Mstrict -ce 'my($xlink,@xlinkpaths)' -e syntax OK
but in
my @xlinks = (`cmd to get xlinks`) ;the parens are gratuitous.
foreach $xlink (@xlinks) { @xlinkpaths = }
Missing right hand side of assignment. Ok, you ask for that in
1)
First, you don't want to assign to @xlinkpaths, but append to it. Use push. Then, to get the text after /./, you could use a regular expression:
foreach $xlink (@xlinks) { push @xlinkpaths, $xlink =~ m{incl -s streamname /./(.+)}; }
Look up the match operator m// (used as m{} here) in perlop.
The match operator returns 1 upon success; if used in list context (this is the case with push) it returns 1, if no captures are used (a capture is what is caught by parens, in the above code (.+), otherwise it returns the captures.
Captures are stored in $1, $2, $3, ...
The above code could have been written as
foreach $xlink (@xlinks) { $xlink =~ m{incl -s streamname /./(.+)}; push @xlinkpaths, $1; }
which gives you the possibility to not include empty matches via a statement modifier:
push @xlinkpaths, $1 if $1;
2)
As you have already learned by now, use push to append to an existing array. Use unshift to prepend to an existing array. Your final @xlinkpaths looks like prepending.
unshift @exclpaths, @xlinkpaths;
Your code - after cleanup and inserting mising bits - could look like
use strict; use warnings; my( $xlink,@xlinkpaths ); my $stream = streamname; my @xlinks = (`cmd to get xlinks`) ; foreach $xlink (@xlinks) { push @xlinkpaths, $xlink =~ m{incl -s streamname /./(.+)}; } my @exclpaths = ( "wefwfewf/fewfff/", "btrtbrtb/gbrgbrg/rttty/", ); unshift @exclpaths, @xlinkpaths;
and appears to do what you want.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl: Split/format the output and append it to an array
by sravs448 (Acolyte) on Sep 12, 2014 at 15:03 UTC | |
by shmem (Chancellor) on Sep 12, 2014 at 19:52 UTC |