我声明了以下数据:
#Content of "file.dat"
#===========================
#Chaplin Charlie Basel
#Estevez Emilio Santa Manica
#Sarte Jean Paul Montmarte
#Rikard Frank Amsterdam
#Rodin Paul Montmarte
use strict;
use warnings;
use Data::Dumper;
my $file = "file.dat";
open NAMES_DAT, "file.dat" or die "Cannot open $file!\n";
print "\nInitial data.\n";
my @lines;
while ( my $line = <NAMES_DAT> ) {
chomp($line);
print $line . "\n";
push(@lines, $line);
}
print "Num. reg: " . scalar(@lines) ."\n";
#We've been using an array of strings, now, we will transform
#this into an array of hashes, for direct access to each field.
my $account = {};
my $id = '';
foreach my $line (@lines) {
my @record = split(' ', $line);
my $set = {};
$set = { firstname => $record[1],
town => $record[2],
};
$id = $record[0];
$account->{$id} = $set;
}
现在,我想对变量$ account进行排序,以获得由田野镇订购的新帐户。如何使用此类数据进行函数排序?谢谢大家。
答案 0 :(得分:1)
$ account中没有订单:它是对哈希的引用,哈希没有任何顺序。
你的意思是你想要城镇作为钥匙。但这些城镇背后应该是什么? 假设我们想要名单和姓氏列表
一种方法是:
my $h ;
for my $name (keys %{ $account}) {
my $town = $account->{$name}{'town'} ;
my $firstname = $account->{$name}{'firstname'} ;
push @{ $h->{$town}{'firstnames'} }, $firstname ;
push @{ $h->{$town}{'names'} }, $name ;
}
给出:
$VAR1 = {
'Basel' => {
'names' => [
'Chaplin'
],
'firstnames' => [
'Charlie'
]
},
'Montmarte' => {
'names' => [
'Rodin',
'Sarte'
],
'firstnames' => [
'Paul',
'Jean-Paul'
]
},
'Santa-Manica' => {
'names' => [
'Estevez'
],
'firstnames' => [
'Emilio'
]
},
'Amsterdam' => {
'names' => [
'Rikard'
],
'firstnames' => [
'Frank'
]
}
};