2017-03-01 85 views
0

陣列的哈希我有一個輸入文件:遍歷從功能

id_1 10 15 20:a:4:c 
id_2 1 5 2:2:5:c 
id_3 0.4 3 12:1:4:1 
id_4 18 2 9:1:0/0:1 
id_5 a b c:a:foo:2 

我有很多這種類型的文件,我想在不同的程序來解析,所以我想打一個返回哈希函數與容易訪問。

我以前沒有寫過這樣的函數,我不確定如何正確訪問返回的散列。下面是我到目前爲止有:

Library_SO.pm

#!/urs/bin/perl 

package Library_SO; 
use strict; 
use warnings; 

sub tum_norm_gt { 

    my $file = shift; 
    open my $in, '<', $file or die $!; 

    my %SVs; 
    my %info; 

    while(<$in>){ 
     chomp; 

     my ($id, $start, $stop, $score) = split; 
     my @vals = (split)[1..2]; 

     my @score_fields = split(/:/, $score); 

     $SVs{$id} = [ $start, $stop, $score ]; 

     push @{$info{$id}}, @score_fields ; 
    } 
    return (\%SVs, \%info); 
} 

1; 

我的主腳本: get_vals.pl

#!/urs/bin/perl 

use Library_SO; 
use strict; 
use warnings; 

use feature qw/ say /; 
use Data::Dumper; 

my $file = shift or die $!; 

my ($SVs, $info) = Library_SO::tum_norm_gt($file); 

print Dumper \%$SVs; 
print Dumper \%$info; 

# for (keys %$SVs){ 
# say; 
# my @vals = @{$SVs{$_}}; <- line 20 
# } 

我把這個用: perl get_vals.pl test_in.txt

The Dumper輸出是我所希望的,但是當我嘗試迭代返回的散列(?)並訪問值(例如,如在註釋部分)我得到:

Global symbol "%SVs" requires explicit package name at get_vals.pl line 20. 
Execution of get_vals.pl aborted due to compilation errors. 

我是否完全顛倒了?

+0

嘗試'print Dumper($ SVs);'看看如果這能解決您的錯誤或它會給你關於返回的想法來自sub的數據。 – AbhiNickz

+2

嘗試添加引用解引用運算符' - >':'my @vals = @ {$ SVs - > {$ _}}' –

回答

3

你的庫函數返回兩個hashrefs。如果您現在想要訪問這些值,則必須解散hashref:

my ($SVs, $info) = Library_SO::tum_norm_gt($file); 

#print Dumper \%$SVs; 
# Easier and better readable: 
print Dumper $SVs ; 

#print Dumper \%$info; 
# Easier and better readable: 
print Dumper $info ; 


for (keys %{ $SVs }){ # Better visual derefencing 
    say; 
    my @vals = @{$SVs->{$_}}; # it is not $SVs{..} but $SVs->{...} 
} 
+0

好的 - 爲什麼需要使用' - >'? – fugu

+0

看看[man perlref - 使用引用](http://perldoc.perl.org/perlref.html#Using-References)第3點 – dgw