2012-05-31 44 views
10

我在網上查看perl代碼,遇到了以前沒有見過的東西,無法找到它在做什麼(如果有的話)。perl中的雙花括號

if($var) {{ 
    ... 
}} 

有沒有人知道雙曲花括號是什麼意思?

+5

我不認爲他們做任何事情。我認爲它們相當於在if塊中添加另一個代碼塊。 – gpojd

回答

11

這是一個通常與do一起使用的技巧,請參閱chapter Statement Modifiers in perlsyn

也許作者想跳出next之類的東西。

+0

這似乎是代碼在做什麼。最後一個關鍵字用在if代碼中的代碼中。謝謝! – Chris

4

if情況下,他們很可能等同於單一的大括號(但是這取決於塊內有什麼和if外,比照

perl -E ' say for map { if (1) {{ 1,2,3,4 }} } 1 .. 2' 

)。有理由使用雙花括號,但是,nextdo,請參閱perlsyn。例如,嘗試多次運行:

perl -E 'if (1) {{ say $c++; redo if int rand 2 }}' 

並嘗試用單個替換雙花括號。

+0

這是一個很好的例子。 – ysth

0

沒有更多的代碼,很難說它們被用於什麼。這可能是一個錯字,或者它可能是一個裸體,請參閱chapter 10.4 The Naked Block Control Structure in Learning Perl

裸體模塊爲塊內的變量添加了詞彙範圍。

+0

'if'後的第一組大括號是否已經提供了範圍界定?爲什麼要窩?我基本上對perl一無所知,所以也許這對人們是顯而易見的,但對我來說不是這樣! –

+2

@ChrisFarmer:因爲'if(1){{my $ x = 1; } {my $ x = 2; }}' – choroba

+0

通過添加第二個作用域,您可以重新分配'$ var'並以在if塊之外不可見的方式在裸塊中使用它。 –

14

那裏有兩個陳述。 「if」聲明和bare block。裸塊是僅執行一次的循環。

say "a"; 
{ 
    say "b"; 
} 
say "c"; 

# Outputs a b c 

但作爲環,它們影響nextlastredo

my $i = 0; 
say "a"; 
LOOP: { # Purely descriptive (and thus optional) label. 
    ++$i; 
    say "b"; 
    redo if $i == 1; 
    say "c"; 
    last if $i == 2; 
    say "d"; 
} 
say "e"; 

# Outputs a b b c e 

next確實相同last由於沒有下一個元素。)

它們通常用於創建一個詞彙範圍。

my $file; 
{ 
    local $/; 
    open(my $fh, '<', $qfn) or die; 
    $file = <$fh>; 
} 
# At this point, 
# - $fh is cleared, 
# - $fh is no longer visible, 
# - the file handle is closed, and 
# - $/ is restored. 

現在還不清楚爲什麼在這裏使用。


或者,它也可能是一個哈希構造。

sub f { 
    ... 
    if (@errors) { 
     { status => 'error', errors => \@errors } 
    } else { 
     { status => 'ok' } 
    } 
} 

是短期的

sub f { 
    ... 
    if (@errors) { 
     return { status => 'error', errors => \@errors }; 
    } else { 
     return { status => 'ok' }; 
    } 
} 

的Perl偷窺到括號猜測,如果它是一個裸露的循環或哈希構造。既然你沒有提供大括號的內容,我們不能說。

+1

+1提及哈希構造函數的可能性。 – chepner

0

{{可用於突破「if塊」。我有一個包含一些代碼:

if ($entry =~ m{\nuid: ([^\s]+)}) {{ # double brace so "last" will break out of "if" 
    my $uid = $1; 
    last if exists $special_case{$uid}; 
    # .... 

}} 
# last breaks to here