我正在尝试将数组映射到接受2个参数的子例程,我尝试使用php array_map concept但是没有成功:
sub m {
my ($n, $m) = @_;
return("The number $n is called $m in Spanish");
}
sub new_map {
my (@argument) = @_;
my @arg = @argument;
@array = map(m($_, $_), @{ $arg[0] }, @{ $arg[1]});
}
my @arr1 = (1, 2, 3);
my @arr2 = ("uno", "dos");
new_map(\@arr1, \@arr2);
#outputs
#The number 1 is called 1 in Spanish INSTEAD OF 'The number 1 is called uno in Spanish'
#The number 2 is called 2 in Spanish INSTEAD OF 'The number 1 is called dos in Spanish'
有没有办法实现这一目标。
答案 0 :(得分:6)
使用new_map的更新代码可以这样完成:
use Algorithm::Loops 'MapCarMin';
my @arr1 = (1, 2, 3);
my @arr2 = ("uno", "dos");
@array = MapCarMin \&m, \@arr1, \@arr2;
或
sub call_m_over_pair_of_arrays {
my ($arrayref1, $arrayref2) = @_;
map &m($arrayref1->[$_], $arrayref2->[$_]), 0..( $#$arrayref1 < $#$arrayref2 ? $#$arrayref1 : $#$arrayref2 );
}
@array = call_m_over_pair_of_arrays( \@arr1, \@arr2 );
回答原始问题:
括号不会在perl中创建列表或数组;嵌套括号只是扁平成一个列表;你需要这样做:
@array = map( &m(@$_), [ 1, 'uno' ], [ 2, 'dos' ] );
或者这个:
use List::Util 1.29 'pairmap';
@array = pairmap { &m($a, $b) } (1, 'uno', 2, 'dos');
不要命名子程序m
;在m
匹配运算符时发生冲突。 (虽然你仍然可以使用&
调用这样的子程序,但最好不要这样做。)