in reply to Re: Analyse an array and join only some elements of it
in thread Analyse an array and join only some elements of it
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;
|
|---|