Perl:将文件加载到散列中

Perl: Load file into hash

我很难理解 Perl 中散列背后的逻辑。任务是将文件加载到散列中,并将值分配给使用该文件创建的键。

文件包含字母表,每个字母各占一行:

a
b
c
d
e

等等。 当使用 array 而不是哈希时,逻辑很简单:将文件加载到数组中,然后使用一些计数器 ($counter++).

将每个元素与相应的数字打印出来

但现在我的问题是,我如何将文件读入我的散列,分配自动生成的值并按照输出的方式对其进行排序,如下所示:

a:1
b:2
c:3

我尝试先创建数组,然后 link 使用

对其进行哈希处理
%hash = @array

但它使我的哈希不可排序。

有多种方法可以解决这个问题。最直接的方法是在读取文件时将数据加载到哈希中。

my %hash;
while(<>)
{
    chomp;
    $hash{$_} = $.;    #Use the line number as your autogenerated counter.
}

如果您已经有一个填充数组,您也可以执行类似的逻辑。

for (0..$#array)
{
    $hash{$array[$_]} = $_;
}

尽管如此,如果您处于那种情况,map 是更好的处理方式。

%hash = map { $array[$_] => $_ } @array;

将散列视为一组对(键、值),其中键必须是唯一的。你想一次一行地读取文件,并在散列中添加一对:

$record = <$file_handle>;
$hash{$record} = $counter++;

当然,您可以一次将整个文件读入一个数组,然后分配给您的散列。但是解决方法不是:

@records = <$file_handle>;
%hash = @records;

...如您所见。如果你用 (key, value) 对来思考,你会发现上面的等价于:

$hash{a} = 'b';
$hash{c} = 'd';
$hash{e} = 'f';
...

等等。您仍然需要一个循环,或者像这样的显式循环:

foreach my $rec (@records)
{
    $hash{$rec} = $counter++;
}

或像下面这样的隐含的:

%hash = map {$_ => $counter++} @records;
# or:
$hash{$_} = $counter++  for @records;

此代码应生成正确的输出,其中 my-text-file 是您的数据文件的路径:

my %hash;
my $counter = 0;
open(FILE, "my-text-file");
while (<FILE>) {
 chomp;
 $counter++;
 $hash{$_} = $counter;
}
# Now to sort
foreach $key (sort(keys(%hash))) {
 print $key . ":" . $hash{$key} . "\n";
}

我假设您想按字母顺序对哈希进行排序。 keys(%hash)values(%hash) return 分别将 %hash 的键和值作为数组。 运行 该文件上的程序:

f
a
b
d
e
c

我们得到:

a:2
b:3
c:6
d:4
e:5
f:1

希望对您有所帮助。