I am currently having a very simple problem with capturing the output from a backticked shell command. I apologize that the problem is rather simple.
I have some sorted array (@valid_runs) which I know contains consecutive, duplicate elements. I want to use backticks to echo this array to uniq. I want to capture the STDOUT in an array. I attempt to do so like this.
@unique_valids = `echo '@valid_runs' | uniq`;
print @unique_valids;
This print statement yields nothing. For that matter neither does this.
@unique_valids = `echo '@valid_runs'`;
print @unique_valids;
I know how to use uniq and echo. This seems rather odd to me. I would think this has more to do with perl arrays than proper use of those commands. I have searched around a bit elsewhere, so please don't pelt me with downvotes just because the solution might seem trivial. Thanks again for your time.
NOTE on solutions: TLP's solution is the most straightforward as far handling the uniq problem. I am being rather flexible, since all responses suggested not making a system call for this problem. If Perl's uniq function the same as Unix's uniq then the array ought to remain sorted.
John Corbett's solution works well if you don't care about a sorted result.
Using system calls for something that can easily be accomplished with perl code is not a good idea. The module List::MoreUtils has a uniq function that does what you require:
use List::MoreUtils qw(uniq);
my @unique = uniq @runs;
The subroutine inside the module itself is very simple, though, exactly like theglauber's answer:
sub uniq (@) {
my %seen = ();
grep { not $seen{$_}++ } @_;
}
you should just store the array into a hash, because hash keys are always unique. You can do that like this:
my %temp_hash = map { $_ => 1 } @valid_runs;
my @unique_valids = keys %temp_hash;
that's the perl way of doing it anyway. There's no need to use back tics here (I try to avoid those as much as I can).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With