in reply to Analyse an array and join only some elements of it

my @dna_chunks = ...; sub your_test { my $string = shift; # do your test here, and return 1 if it passes } my @used = grep your_test($_), @dna_chunks; my $long_string = join '', @used; print "Used ", scalar(@used), " chunks, ",@dna_chunks - @used, " disca +red";

See grep for details.

Replies are listed 'Best First'.
Re^2: Analyse an array and join only some elements of it
by tobyink (Canon) on Jun 15, 2012 at 13:52 UTC

    The combination of join and grep sounds like it will do what you want. (map and sort and some of their friends from List::Util and List::MoreUtils are also often useful, but don't sound needed in your case.)

    The following example uses join and grep to filter the numbers from 1 to 20 for primes, then join the primes together into a string separated by semicolons.

    sub is_prime { my $num = shift; return if $num == 1; # 1 is not prime die "usage: is_prime(NATURAL NUMBER)" unless $num =~ /^[1-9][0-9]*$/; for my $div (2 .. sqrt $num) { return if $num % $div == 0; } return 1; } my @numbers = 1 .. 20; print join ";", grep { is_prime($_) } @numbers;
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'