2010-08-25 34 views
3

我基本上試圖將一個字符串和一個散列傳遞給perl中的一個子例程。無法將一個散列和一個字符串傳遞給一個函數,一起在perl中!

sub coru_excel { 
    my(%pushed_hash, $filename) = @_; 
    print Dumper(%pushed_hash); 
} 

但似乎數據越來越混亂起來。轉儲的數據還包括$filename。這裏是輸出。

................... 
$VAR7 = 'Address'; 
$VAR8 = [ 
      '223 VIA DE 
................ 
     ]; 
$VAR9 = 'data__a.xls'  <----- $filename 
$VAR10 = undef; 
$VAR11 = 'DBA'; 
$VAR12 = [ 
      'J & L iNC 
.................. 
     ]; 

這裏是我如何調用子程序。

coru_excel(%hash, "data_".$first."_".$last.".xls"); 
+2

這是諸如此類的事情,我們在_Intermediate Perl_覆蓋。 :) – 2010-08-25 15:47:30

回答

9

參數作爲一個無差異列表傳遞給子例程。

一種解決方法是顛倒參數的順序,使標量第一。

sub coru_excel { 
    my($filename, %pushed_hash) = @_; 
} 

coru_excel("FILE_NAME", %hash); 

另一種方法是按引用傳遞哈希:

sub coru_excel { 
    my($pushed_hash_ref, $filename) = @_; 
} 

coru_excel(\%hash, "FILE_NAME"); 
5

你要通過哈希作爲參考:

coru_excel(\%hash, "data_".$first."_".$last.".xls"); 

你使用這樣的:

sub coru_excel { 
    my($pushed_hash_ref, $filename) = @_; 
    my %pushed_hash = %{$pushed_hash_ref}; 

    print Dumper(%pushed_hash); # better: \%pushed_hash or $pushed_hash_ref 
} 

請參閱perlreftut有關參考文獻的教程以及perlref以獲取更多信息。

Dumper當您傳遞散列(或數組)引用時,也會產生更好的可用信息。

6

你可以通過哈希作爲參考:

sub coru_excel { 
    my($pushed_hashref, $filename) = @_; 
    print Dumper(%$pushed_hashref); 
} 

coru_excel(\%my_hash, $file); 

或者初始化哈希之前,你可以給予特殊待遇,以最終參數:

sub coru_excel { 
    my $filename = pop @_; 
    my(%pushed_hash) = @_; 
    print Dumper(%pushed_hash); 
} 
2

一個小程序,演示如何做這在傳遞散列和在子例程中移動以提取參數時使用引用符號。

#!/usr/bin/perl -w 
use strict; 
sub coru_excel(%$); 
my %main_hash = ('key1' => 'val1', 'key2' => 'val2'); 
my $first = "ABC"; 
my $last = "xyz"; 
coru_excel(\%main_hash, "data_" . $first . "_" . $last . ".xls"); 
exit; 

sub coru_excel(%$) 
{ 
    my %passed_hash = %{(shift)}; 
    my $passed_string = shift; 
    print "%passed_hash:\n"; 
    for my $k (keys %passed_hash) { 
     print " $k => $passed_hash{$k}\n"; 
    } 
    print "\$passed_string = $passed_string\n"; 
    return; 
} 
+0

在這個例子中,函數原型是否有用於任何有用的目的? – FMc 2010-08-26 08:46:33

+0

@FM:它有害嗎? – GreenMatt 2010-08-26 11:21:09

相關問題