Cari di Perl 
    Perl User Manual
Daftar Isi
(Sebelumnya) Get/set subroutine or variable ...Postpone load of modules until ... (Berikutnya)
Pragmas

Replace functions with ones that succeed or die with lexical scope

Daftar Isi

NAME

autodie - Replace functions with ones that succeed or die with lexical scope

SYNOPSIS

  1. use autodie; # Recommended: implies 'use autodie qw(:default)'
  2. use autodie qw(:all); # Recommended more: defaults and system/exec.
  3. use autodie qw(open close); # open/close succeed or die
  4. open(my $fh, "<", $filename); # No need to check!
  5. {
  6. no autodie qw(open); # open failures won't die
  7. open(my $fh, "<", $filename); # Could fail silently!
  8. no autodie; # disable all autodies
  9. }

DESCRIPTION

  1. bIlujDI' yIchegh()Qo'; yIHegh()!
  2. It is better to die() than to return() in failure.
  3. -- Klingon programming proverb.

The autodie pragma provides a convenient way to replace functionsthat normally return false on failure with equivalents that throwan exception on failure.

The autodie pragma has lexical scope, meaning that functionsand subroutines altered with autodie will only change their behaviouruntil the end of the enclosing block, file, or eval.

If system is specified as an argument to autodie, then ituses IPC::System::Simple to do the heavy lifting. See thedescription of that module for more information.

EXCEPTIONS

Exceptions produced by the autodie pragma are members of theautodie::exception class. The preferred way to work withthese exceptions under Perl 5.10 is as follows:

  1. use feature qw(switch);
  2. eval {
  3. use autodie;
  4. open(my $fh, '<', $some_file);
  5. my @records = <$fh>;
  6. # Do things with @records...
  7. close($fh);
  8. };
  9. given ($@) {
  10. when (undef) { say "No error"; }
  11. when ('open') { say "Error from open"; }
  12. when (':io') { say "Non-open, IO error."; }
  13. when (':all') { say "All other autodie errors." }
  14. default { say "Not an autodie error at all." }
  15. }

Under Perl 5.8, the given/when structure is not available, so thefollowing structure may be used:

  1. eval {
  2. use autodie;
  3. open(my $fh, '<', $some_file);
  4. my @records = <$fh>;
  5. # Do things with @records...
  6. close($fh);
  7. };
  8. if ($@ and $@->isa('autodie::exception')) {
  9. if ($@->matches('open')) { print "Error from open\n"; }
  10. if ($@->matches(':io' )) { print "Non-open, IO error."; }
  11. } elsif ($@) {
  12. # A non-autodie exception.
  13. }

See autodie::exception for further information on interrogatingexceptions.

CATEGORIES

Autodie uses a simple set of categories to group together similarbuilt-ins. Requesting a category type (starting with a colon) willenable autodie for all built-ins beneath that category. For example,requesting :file will enable autodie for close, fcntl,fileno, open and sysopen.

The categories are currently:

  1. :all
  2. :default
  3. :io
  4. read
  5. seek
  6. sysread
  7. sysseek
  8. syswrite
  9. :dbm
  10. dbmclose
  11. dbmopen
  12. :file
  13. binmode
  14. close
  15. fcntl
  16. fileno
  17. flock
  18. ioctl
  19. open
  20. sysopen
  21. truncate
  22. :filesys
  23. chdir
  24. closedir
  25. opendir
  26. link
  27. mkdir
  28. readlink
  29. rename
  30. rmdir
  31. symlink
  32. unlink
  33. :ipc
  34. pipe
  35. :msg
  36. msgctl
  37. msgget
  38. msgrcv
  39. msgsnd
  40. :semaphore
  41. semctl
  42. semget
  43. semop
  44. :shm
  45. shmctl
  46. shmget
  47. shmread
  48. :socket
  49. accept
  50. bind
  51. connect
  52. getsockopt
  53. listen
  54. recv
  55. send
  56. setsockopt
  57. shutdown
  58. socketpair
  59. :threads
  60. fork
  61. :system
  62. system
  63. exec

Note that while the above category system is presently a stricthierarchy, this should not be assumed.

A plain use autodie implies use autodie qw(:default). Note thatsystem and exec are not enabled by default. system requiresthe optional IPC::System::Simple module to be installed, and enablingsystem or exec will invalidate their exotic forms. See BUGSbelow for more details.

The syntax:

  1. use autodie qw(:1.994);

allows the :default list from a particular version to be used. Thisprovides the convenience of using the default methods, but the suretythat no behavorial changes will occur if the autodie module isupgraded.

autodie can be enabled for all of Perl's built-ins, includingsystem and exec with:

  1. use autodie qw(:all);

FUNCTION SPECIFIC NOTES

flock

It is not considered an error for flock to return false if it failsdue to an EWOULDBLOCK (or equivalent) condition. This means one canstill use the common convention of testing the return value offlock when called with the LOCK_NB option:

  1. use autodie;
  2. if ( flock($fh, LOCK_EX | LOCK_NB) ) {
  3. # We have a lock
  4. }

Autodying flock will generate an exception if flock returnsfalse with any other error.

system/exec

The system built-in is considered to have failed in the followingcircumstances:

  • The command does not start.

  • The command is killed by a signal.

  • The command returns a non-zero exit value (but see below).

On success, the autodying form of system returns the exit valuerather than the contents of $?.

Additional allowable exit values can be supplied as an optional firstargument to autodying system:

  1. system( [ 0, 1, 2 ], $cmd, @args); # 0,1,2 are good exit values

autodie uses the IPC::System::Simple module to change system.See its documentation for further information.

Applying autodie to system or exec causes the exoticforms system { $cmd } @args or exec { $cmd } @argsto be considered a syntax error until the end of the lexical scope.If you really need to use the exotic form, you can call CORE::systemor CORE::exec instead, or use no autodie qw(system exec) beforecalling the exotic form.

GOTCHAS

Functions called in list context are assumed to have failed if theyreturn an empty list, or a list consisting only of a single undefelement.

DIAGNOSTICS

  • :void cannot be used with lexical scope

    The :void option is supported in Fatal, but notautodie. To workaround this, autodie may be explicitly disabled untilthe end of the current block with no autodie.To disable autodie for only a single function (eg, open)use no autodie qw(open).

  • No user hints defined for %s

    You've insisted on hints for user-subroutines, either by pre-pendinga ! to the subroutine name itself, or earlier in the list of argumentsto autodie. However the subroutine in question does not haveany hints available.

See also DIAGNOSTICS in Fatal.

BUGS

"Used only once" warnings can be generated when autodie or Fatalis used with package filehandles (eg, FILE). Scalar filehandles arestrongly recommended instead.

When using autodie or Fatal with user subroutines, thedeclaration of those subroutines must appear before the first use ofFatal or autodie, or have been exported from a module.Attempting to use Fatal or autodie on other user subroutines willresult in a compile-time error.

Due to a bug in Perl, autodie may "lose" any format which has thesame name as an autodying built-in or function.

autodie may not work correctly if used inside a file with aname that looks like a string eval, such as eval (3).

autodie and string eval

Due to the current implementation of autodie, unexpected resultsmay be seen when used near or with the string version of eval.None of these bugs exist when using block eval.

Under Perl 5.8 only, autodie does not propagate into string evalstatements, although it can be explicitly enabled inside a stringeval.

Under Perl 5.10 only, using a string eval when autodie is ineffect can cause the autodie behaviour to leak into the surroundingscope. This can be worked around by using a no autodie at theend of the scope to explicitly remove autodie's effects, or byavoiding the use of string eval.

None of these bugs exist when using block eval. The use ofautodie with block eval is considered good practice.

REPORTING BUGS

Please report bugs via the CPAN Request Tracker athttp://rt.cpan.org/NoAuth/Bugs.html?Dist=autodie.

FEEDBACK

If you find this module useful, please consider rating it on theCPAN Ratings service athttp://cpanratings.perl.org/rate?distribution=autodie .

The module author loves to hear how autodie has made your lifebetter (or worse). Feedback can be sent to<[email protected]>.

AUTHOR

Copyright 2008-2009, Paul Fenwick <[email protected]>

LICENSE

This module is free software. You may distribute it under thesame terms as Perl itself.

SEE ALSO

Fatal, autodie::exception, autodie::hints, IPC::System::Simple

Perl tips, autodie athttp://perltraining.com.au/tips/2008-08-20.html

ACKNOWLEDGEMENTS

Mark Reed and Roland Giersig -- Klingon translators.

See the AUTHORS file for full credits. The latest version of thisfile can be found athttp://github.com/pfenwick/autodie/tree/master/AUTHORS .

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Get/set subroutine or variable ...Postpone load of modules until ... (Berikutnya)