2012-05-04 11 views
5

Questo costrutto è abbastanza comune in Perl:perl "o" gestione errori: multi-statement su errore possibile?

opendir (B,"/somedir") or die "couldn't open dir!"; 

Ma questo non sembra funzionare:

opendir (B, "/does-not-exist ") or { 
    print "sorry, that directory doesn't exist.\n"; 
    print "now I eat fugu.\n"; 
    exit 1; 
}; 

E 'possibile che la "o" di gestione degli errori per avere più di un comando?

Compilare il sopra:

# perl -c test.pl 
syntax error at test.pl line 5, near "print" 
syntax error at test.pl line 7, near "}" 
test.pl had compilation errors. 
+2

stampe di errore devono essere inviate a 'stderr', e si dovrebbe usare' die' invece di '' print' + exit'. – ikegami

risposta

14

si può sempre utilizzare do:

opendir (B, "/does-not-exist ") or do { 
    print "sorry, that directory doesn't exist.\n"; 
    print "now I eat fugu.\n"; 
    exit 1; 
} 

Oppure si può usare se/a meno che:

unless (opendir (B, "/does-not-exist ")) { 
    print "sorry, that directory doesn't exist.\n"; 
    print "now I eat fugu.\n"; 
    exit 1; 
} 

Oppure si può oscillare insieme il proprio subroutine:

opendir (B, "/does-not-exist ") or fugu(); 

sub fugu { 
    print "sorry, that directory doesn't exist.\n"; 
    print "now I eat fugu.\n"; 
    exit 1; 
} 

C'è più di un modo per farlo.

+0

Il "più regolare" non funziona, ad esempio, se si usa 'open (my $ B, ...)'. – ikegami

+0

@ikegami Beh, * funziona *, non sarà molto produttivo. Con l'handle di file globale, non dovrebbe importare. – TLP

+0

@TLP a parte il problema dell'ambito, perché consideri la soluzione "a meno" non consigliata? –

-2

gestione delle eccezioni in Perl è fatto con eval()

eval { 
    ... 
} or do { 
    ...Use [email protected] to handle the error... 
}; 
+0

'open' non muore, restituisce semplicemente' undef'. Non c'è niente da prendere usando 'eval'. – chepner