[英]Sorting by a hash value into an reference of an array of hashes
我声明了以下数据:
#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进行排序,以获取由现场城镇订购的新帐户。 如何对此类数据使用函数排序? 谢谢大家
$ 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'
]
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.