[英]Perl nesting hash of hashes
我在根據文本輸入確定如何在perl中創建嵌套哈希時遇到了一些麻煩。
我需要這樣的東西
my % hash = {
key1 => \%inner-hash,
key2 => \%inner-hash2
}
然而我的問題是我不知道apriori會有多少內部哈希。 為此,我編寫了以下片段來測試是否可以在循環中創建str變量,並將其引用存儲在數組中,然后再解除引用。
{
if($line =~ m/^Limit\s+$mc_lim\s+$date_time_lim\s+$float_val\s+$mc\s+$middle_junk\s+$limit \s+$value/) {
my $str = $1 . ' ' . $2 . ' ' . $7;
push (@test_array_reference, \$str);
}
}
foreach (@test_array_reference) {
say $$_;
}
Perl死於標量運行時錯誤。 我在這里有點失落。 任何幫助將不勝感激。
要回答您的第一個(主要?)問題,如果您瀏覽文本並隨時創建它們,則無需知道要創建多少哈希值。 此示例使用以空格分隔的字符串的單詞作為鍵,但您可以使用任何輸入文本作為您的用途。
my $text = 'these are just a bunch of words';
my %hash;
my $hashRef = \%hash; # create reference to initial hash
foreach (split('\s', $text)){
$hashRef->{$_} = {}; # create anonymous hash for current word
$hashRef = $hashRef->{$_}; # walk through hash of hashes
}
您還可以引用任意內部哈希並設置值,
$hash{these}{are}{just}{a}{bunch}{of}{words} = 88;
$hash{these}{are}{just}{a}{bunch}{of}{things} = 42;
$hash{these}{things} = 33;
要想象這一點, Data:Dumper
可能有所幫助,
print Dumper %hash;
哪個生成,
$VAR1 = 'these';
$VAR2 = {
'things' => 33,
'are' => {
'just' => {
'a' => {
'bunch' => {
'of' => {
'things' => 42,
'words' => 88
}
}
}
}
}
};
創建哈希散列非常簡單:
my %outer_hash = {};
並非完全必要,但這基本上意味着哈希的每個元素都是對另一個哈希的引用。
想象一下由員工編號鍵入的員工哈希:
$employee{$emp_num}{first} = "Bob";
$employee{$emp_num}{last} = "Smith";
$employee{$emp_num}{phones}{cell} = "212-555-1234";
$employee{$emp_num}{phones}{desk} = "3433";
這種表示法的問題在於它在一段時間后難以閱讀。 輸入箭頭符號:
$employee{$emp_num}->{first} = "Bob";
$employee{$emp_num}->{last} = "Smith";
$employee{$emp_num}->{phones}->{cell} = "212-555-1234";
$employee{$emp_num}->{phones}->{desk} = "3433";
像這樣的復雜結構的一個大問題是你失去了use strict
查找錯誤的能力:
$employee{$emp_num}->{Phones}->{cell} = "212-555-1234";
哎呦! 我使用的是Phones
而不是phones
。 當您開始使用這種類型的復雜結構時,您應該使用面向對象的語法。 幸運的是, perlobj教程很容易理解。
順便說一下,復雜的數據結構處理和使用面向對象的Perl的能力使你進入大聯盟。 這是編寫更強大,更復雜的Perl的第一步。
my $hashref = { hash1 => { key => val,... },
hash2 => { key => val,..} };
你也可以在你的正則表達式中使用m//x
修飾符,它幾乎不可讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.