Extract the strings from nested arrays in Perl.
It prints: a, b, c, d, E
use strict;
use warnings;
use feature qw(say signatures current_sub);
no warnings qw(experimental::signatures);
my $nested = [1, 'a', [2, 3, 'b'], [4, [5, 6, 7, ['c']], [7, [8, 9, [10, 'd']]], 11, 'E']];
print join ', ', @{ extract_strings($nested) };
sub extract_strings($input) {
my @output = ();
my $loop = sub ($val) {
if (ref $val eq 'ARRAY') {
__SUB__->($_) for @{ $val };
} else {
push(@output, $val) if $val =~ /^[a-zA-Z]/;
}
};
$loop->($input);
return \@output;
}
Any idea for improvement without not core dependencies?
flattenmight be improved toextract_strings? If wanted, speed could be improved by usingInline::Cor XS. \$\endgroup\$push(@output, $val) if /^[a-zA-Z]/;vspush(@output, $val) if $val =~ /^[a-zA-Z]/;I don't understand why this actually work. What is$_in theelse? I'll edit the function. \$\endgroup\$