【发布时间】:2013-12-04 15:23:18
【问题描述】:
我声明了以下数据:
#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 进行排序,以得到一个按字段 town 排序的新变量。如何对此类数据使用函数排序?谢谢大家。
【问题讨论】:
-
我猜你有
Sartre和Montmartre和r。那么你在空间分割时会遇到Jean Paul的问题(除了他的名字是Jean-Paul) -
你说得对,我没有意识到...我必须以另一种方式来拆分行...无论如何重点是如何排序?
-
好的,解压解决方案; ($surname, $name, $town) = unpack("A20 A20 A20", $_);
标签: arrays perl sorting hash reference