Join an array using a block and not an expression in Perl
I'm trying to join an array this way:
@cols = (1,2,3,4);
my $s = join("|$_", @cols);
print $s;
and I expect the following output:
1|2|3|4
but that doesn't work.
I was also looking for some reduce-like function but I can't find one nor I know how to write one in Perl.
Using CPAN is not an option as this program will be executed in computers I cannot install anything else.
What other similar function can I use for that purpose? How can I write that generalized jo开发者_JAVA百科in or reduce function in Perl?
Thanks.
I suspect you want:
my $s = join('|', @$hr{@cols} );
With reduce:
use List::Util 'reduce';
my $s = reduce { "$a|$hr->{$b}" } '', @cols;
(though that produces a leading |).
List::Util
(which is core not CPAN, though you shouldn't ever give up on CPAN) provides a reduce
function. If you provide an input / desired output perhaps I can mock up an example for you.
Looking at ysth's answer gives me another guess at what you want:
my $s = join("|", map { $hr->{$_} } @cols);
again, with more context perhaps we can help more.
Edit: As per the OP's edit, you really are just looking for the simple join
function. Unlike map, it doesn't need any $_
, it automatically joins every element.
my $s = join("|", @cols);
精彩评论