2014-10-22 60 views
2

我繼承形式的功能:

sub func($$) { 

} 

我更習慣於看到:

sub func { 
    ## then extract params using shift for example 
} 

我擡頭$$,這是獲取當前的進程ID的方法。但是看看這個函數看起來不像進程ID這裏使用。 $$在這種情況下意味着什麼?

我感到困惑的功能是下面的parseMessage。爲什麼($$)

use FileHandle; 

# The structure of function is pretty much like this - names changed only 
sub parseMessage($$) 
{ 
    my $string = shift; 
    my $fileHandle = shift; 

    my $Message = undef; 

    # parseAMessage and parseBMessage are functions to extract specific types of messages from file 
    if (($Message = parseAMessage($string, $fileHandle)) 
    || ($Message = parseBMessage($string, $fileHandle))) 
    { 

    } 

    return $Message; 
} 


sub parseAMessage($$) 
{ 
} 

sub parseBMessage($$) 
{ 
} 

# The function seems to use arguments arg1: string from file, arg2: filehandle of file 
# presumably idea behind this is to process current line in file but also have access to file 
# handle to move to next line where required. So the way I am calling this is probably not 
# great Perl - I am a beginner perler 
$fh = FileHandle->new; 
    if ($fh->open("< myfile.log")) { 
     # here we evaluate the file handle in a scalar context to get next line 
     while($line = <$fh>) { 
      parseMessage($line, $fh); 
      #print <$fh>; 
     } 

     $fh->close; 
    } 
    print "DONE\n"; 
1; 
+6

http://perldoc.perl.org/perlsub.html#Prototypes – Quentin 2014-10-22 10:40:14

+3

HTTP:/ /stackoverflow.com/q/297034/1030675 – choroba 2014-10-22 11:50:55

回答

3

它們是原型,並定義函數作爲參數(不安全..)。

它允許你定義函數,如內置函數,所以你可以打電話給你的sub doSomething,就像你打電話print

doSomething($scalar)doSomething $scalar會產生相同的結果,如相對於print($scalar)print $scalar

按照上述的意見:http://perldoc.perl.org/perlsub.html#Prototypes

+1

'print'可能不是一個很好的例子,因爲它沒有特殊的參數解析,除了'print'沒有參數就像'print $ _'那樣。 (如果你真的想爲你自己的函數,你可以用'(_ @)'的原型來實現它。)類似於'push'的東西會是一個更有趣的例子(事實上,這就是perlsub節你鏈接到使用)。 – 2014-10-22 15:00:56

+0

@IlmariKaronen你可能是對的,但它是第一個想到的,不想過度使用map/grep/array函數 – 2014-10-22 15:26:35

+1

實際上'print'具有非常特殊的參數解析,因爲'print $ fh @ list'和'print {$ fh} @ list'形式,這不能用原型來模擬。 [也見這個答案](http://stackoverflow.com/questions/26368555/subroutines-that-take-an-optional-block-parameter)。 – tobyink 2014-10-23 12:22:00

相關問題