Ivan Salazar
Ivan Salazar

Reputation: 296

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 join or reduce function in Perl?

Thanks.

Upvotes: 0

Views: 123

Answers (2)

Joel Berger
Joel Berger

Reputation: 20280

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);

Upvotes: 0

ysth
ysth

Reputation: 98398

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 |).

Upvotes: 2

Related Questions