每当你对自己说我怎样才能快速找到列表中的东西时,你应该对自己说Hash!。
让我们将@toremove 列表转换为哈希。我们可以使用map 命令来做到这一点。 map 命令起初有点吓人,我不相信它的联机帮助页能做到这一点。其实没那么复杂:
@some_hash_or_array = map { .... } @original_array;
map 接受@original_array 并循环遍历该数组的每个条目。 {...} 是您要在每个条目上运行的小程序。
您可以将map 视为某事,如下所示:
my @original_array = qw( ... );
my @some_hash_or_array;
for my $entry ( @original_array ) {
push @some_hash_or_array, { ... };
}
map 之所以有用是因为数组的每个条目都设置为$_,因此操作$_ 可以让您转换数组。
我正在做的是:
my %files = map { $_.".txt" => 1 } @to_remove;
当这个map 命令处理@to_remove 时,它会创建另一个数组,如下所示:
("100.txt" => 1, "102.txt" => 1, "104.txt" => 1, "131.txt" => 1, "156.txt" => 1)
我用这个数组初始化我的%files 哈希。奇数条目是散列的键,键后的偶数条目是数据。
#! /usr/bin/env perl
#
use strict; # Lets you know when you misspell variable names
use warnings; # Warns of issues (using undefined variables)
use feature qw(say);
my @to_remove = qw(100 102 104 131 156);
my %files = map { $_.".txt" => 1 } @to_remove;
while ( my $file = <DATA> ) {
chomp $file;
if ( exists $files{$file} ) {
say qq(File "$file" is in the list);
}
else {
say qq(File "$file" isn't in the list);
}
}
__DATA__
100.txt
203.txt
130.txt
104.txt
150.txt
156.txt
160.txt
这会产生:
File "100.txt" is in the list
File "203.txt" isn't in the list
File "130.txt" isn't in the list
File "104.txt" is in the list
File "150.txt" isn't in the list
File "156.txt" is in the list
File "160.txt" isn't in the list
您需要这样做:
#! /usr/bin/env perl
#
use strict; # Lets you know when you misspell variable names
use warnings; # Warns of issues (using undefined variables
use autodie; # Automatically kills the program if opens fail
use feature qw(say);
my @to_remove = qw(100 102 104 131 156);
opendir my $dir_fh, "dir_name";
my %files = map { $_.".txt" => 1 } @to_remove;
while ( my $file = < $dir_fh > ) {
if ( exists $files{$file} ) {
say qq(File "$file" is in the list);
}
else {
say qq(File "$file" isn't in the list);
}
}