Feeds:
Posts
Comments

Posts Tagged ‘perl’

Error handling in Perl

  • Using unless
    • The unless is the logical opposite to if. Statements can completely bypass the success status and only be executed if the expression returns false.
      • example: die “Error message\n”unless(chdir(“dir”))
      • the unless statement is best used when you want to raise an error only if the expression fails.
  • Using the conditional operator
    • For some short tests, you can use the conditional operator
      • example: print (exists($hash{$key}))
  • Using Warn function
    • Warn function just raises a warning, a message is printed to STDERR, but no further action is taken
      • example: chdir(“dir”) or warn “warn message”;
  • Using Die function
    • Die function works like warn, except that is also calls exit, within a normal script, this function has the effect of immediately terminating execution.
      • example: chdir(“dir”) or die “die message”;
  • Using Carp function
    • Carp function is the basic equivalent of warn and prints the message to STDERR without existing the script and printing the script name
      • example: carp “error message”; will result in “error message, at scriptname.pl line number”
  • Using Cluck function
    • Cluck function is a sort of supercharged carp, it follows the same basic principle but also prints a stack trace of all the modules that led to the function being called, including the information on the original script.
  • Using Croak function
    • Croak function is the equivalent of die. it reports the caller one level up. Like die, this function also exists the script after reporting the error to STDERR.
Advertisements

Read Full Post »

Tie tech in Perl

hide an object class in a simple variable::::::{ tie $scalar, ‘package’, ARGUMENTS… }

——————————————————————————————————————————————————

The tie() function binds a variable to a class (package) that will provide the implementation for access methods for that variable. Once this magic has been performed, accessing a tied variable automatically triggers method calls in the proper class. The complexity of the class is hidden behind magic methods calls. The method names are in ALL CAPS, which is a convention that Perl uses to indicate that they’re called implicitly rather than explicitly–just like the BEGIN() and END() functions.

  1. Tying scalar:::
  2. Tying arrays:::
  3. Tying hashes:::
  4. Tying filehandle:::

——————————————————————————————————————————————————

Arrays::::::

perl array tying

Hashes::::::

perl hash tie

FileHandles::::::

perl filehandle tying

Read Full Post »