Perl 中透過 local() 實現臨時值
在 Perl 中,local 主要用於當變數的當前值必須對已呼叫的子例程可見時。Perl local 只向全域性(含義是包)變數提供臨時值。這被稱為動態作用域。詞法作用域由 my 完成,其功能更類似於 C 的 auto 宣告
如果為 local 提供了多個變數或表示式,則必須將其放在括號中。此運算子透過將那些變數的當前值儲存在其隱藏堆疊中的引數列表中,並在退出塊、子例程或 eval 時恢復它們而起作用。
示例
我們檢視以下示例以區分全域性變數和區域性變數 −
#!/usr/bin/perl # Global variable $string = "Hello, World!"; sub PrintHello { # Private variable for PrintHello function local $string; $string = "Hello, Perl!"; PrintMe(); print "Inside the function PrintHello $string\n"; } sub PrintMe { print "Inside the function PrintMe $string\n"; } # Function call PrintHello(); print "Outside the function $string\n";
輸出
當執行以上程式時,會生成以下結果 −
Inside the function PrintMe Hello, Perl! Inside the function PrintHello Hello, Perl! Outside the function Hello, World!
廣告