Perl 对数组的引用数组进行排序

标签 perl sorting reference

我对 Perl 比较陌生。我有一个名为 $TransRef 的数组的引用,其中包含对数组的引用。我的目标是编写一个子程序,将 $TransRef 参数作为其唯一参数,按第二个元素(字符串)对底层数组的引用进行排序,并将输出设置回 $TransRef 引用。有人可以展示如何在 Perl 中完成此操作吗?

这里是一些生成 $TransRef 的代码。它尚未经过测试,可能存在一些错误:

# Parse the data and move it into the Transactions container.
for ($Loop = 0; $Loop < 5; $Loop++)
{
   $Line = $LinesInFile[$Loop];
   # Create an array called Fields to hold each field in $Line.
   @Fields = split /$Delimitor/, $Line;  
   $TransID = $Fields[2];
   # Save a ref to the fields array in the transaction list.
   $FieldsRef = \@Fields;
   ValidateData($FieldsRef);
   $$TransRef[$Loop] = $FieldsRef;
}
SortByCustID($TransRef);

sub SortByCustID()
{
   # This sub sorts the arrays in $TransRef by the 2nd element, which is the cust #.
   # How to do this?
   my $TransRef = @_;
   ...
}

最佳答案

非常简单:

sub sort_trans_ref {
    my $transRef = shift;
    @$transRef = sort { $a->[1] cmp $b->[1] } @$transRef;
    return $transRef;
}

虽然对我来说不修改原始数组会更自然:

sub sort_trans_ref {
    my $transRef = shift;
    my @new_transRef = sort { $a->[1] cmp $b->[1] } @$transRef;
    return \@new_transRef;
}

关于Perl 对数组的引用数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12590318/

相关文章:

perl - 禁用 HTTP 请求中的 URL 编码

linux - 在 Linux 中解析

python - 对文本行进行分组,如果 A=B 且 B=C,则 A=C

c++ - 如果我不使用引用,为什么这段代码不能编译?

c++ - 修改通过引用传递的变量

python - 如何在命令行上处理 utf8(使用 Perl 或 Python)?

arrays - 重新排序用于创建 subview 的数组后,Ember View 未更新

c++ - 我应该使用哪个数据集?

c++ - 支持引用、值和指针的模板函数?

perl - 使用 WWW::Mechanize 登录