2013-10-11 31 views
3

我有一個perl腳本,我正在讀取給定目錄中的文件,然後將這些文件放入數組中。然後,我希望能夠將這些數組元素移動到perl哈希中,其中數組元素是哈希值,併爲每個哈希值自動分配數字鍵。自動增加perl散列中的數字鍵值?

下面的代碼:

# Open the current users directory and get all the builds. If you can open the dir 
    # then die. 
    opendir(D, "$userBuildLocation") || die "Can't opedir $userBuildLocation: $!\n"; 
    # Put build files into an array. 
    my @builds = readdir(D); 
    closedir(D); 
    print join("\n", @builds, "\n"); 

此打印出來:

test.dlp 
    test1.dlp 

我想利用這些值,並將其插入到一個哈希,看起來就像這樣:

my %hash (
      1 => test.dlp 
      2 => test1.dlp 
     ); 

我希望數字鍵可以自動遞增,具體取決於在給定目錄中可以找到多少個文件。

我只是不確定如何讓自動遞增鍵設置爲散列中每個項目的唯一數值。

回答

6

我不知道理解的需要,但這應該做

my $i = 0; 
my %hash = map { ++$i => $_ } @builds; 

另一種方式來做到這一點

my $i = 0; 
for(@builds) { 
    $hash{++$i} = $_; 
} 
+0

第一個選項完美的作品!非常感謝。 –

6

最簡單和枯燥的方式:

my %hash; 
for (my $i=0; $i<@builds; ++$i) { 
    $hash{$i+1} = $builds[$i]; 
} 

或者如果您願意:

foreach my $i (0 .. $#builds) { 
    $hash{$i+1} = $builds[$i]; 
} 

我喜歡這種方法:

@hash{[email protected]} = @builds; 
+0

這是一個更整潔:] –

2

另:

my %hash = map { $_+1, $builds[$_] } 0..$#builds; 

或:

my %hash = map { $_, $builds[$_-1] } [email protected];