【发布时间】:2015-04-25 06:22:13
【问题描述】:
我目前正在编写一个 perl 脚本,其中我有一个引用数组(学生)的引用。将哈希引用添加到数组后。现在我添加对学生数组的引用,然后询问用户如何对它们进行排序。这就是令人困惑的地方。我不知道如何尊重排序数组。使用 dumper 我可以获得排序后的数组,但输出是无组织的。 如何在排序后尊重哈希引用数组?
#!bin/usr/perl
use strict;
use warnings;
use Data::Dumper;
use 5.010;
#reference to a var $r = \$var; Deferencing $$r
#reference to an array $r = \@var ; Deferencing @$r
#referenc to a hash $r = \%var ; deferencing %$r
my $filename = $ARGV[0];
my $students = [];
open ( INPUT_FILE , '<', "$filename" ) or die "Could not open to read \n ";
sub readLines{
while(my $currentLine = <INPUT_FILE>){
chomp($currentLine);
my @myLine = split(/\s+/,$currentLine);
my %temphash = (
name => "$myLine[0]",
age => "$myLine[1]",
GPA => "$myLine[2]",
MA => "$myLine[3]"
);
pushToStudents(\%temphash);
}
}
sub pushToStudents{
my $data = shift;
push $students ,$data;
}
sub printData{
my $COMMAND = shift;
if($COMMAND eq "sort up"){
my @sortup = sort{ $a->{name} cmp $b->{name} } @$students;
print Dumper @sortup;
}elsif($COMMAND eq "sort down"){
my @sortdown = sort{ $b->{name} cmp $a->{name} } @$students;
print Dumper @sortdown;
//find a way to deference so to make a more organize user friendly read.
}else{
print "\n quit";
}
}
readLines();
#Output in random, the ordering of each users data is random
printf"please choose display order : ";
my $response = <STDIN>;
chomp $response;
printData($response);
【问题讨论】:
-
print Dumper \@sortdown; -
什么都不做。我试过了。
-
我的错误。
print Dumper(\@sortdown);都一样,我会期待某事,而不是“什么都不做”。 -
“无组织的输出”是什么意思?您是否尝试使用
Dumper获得整洁的格式化输出?
标签: perl