Menu

PERL TUTORIALS - Perl Error Handling

Perl Error Handling

ADVERTISEMENTS

The if statement

if(open(DATA, $file)){
   ...
}else{
   die "Error: Couldn't open the file - $!";
}

ADVERTISEMENTS

open(DATA, $file) || die "Error: Couldn't open the file $!";

ADVERTISEMENTS

The unless function

unless(chdir("/etc")){
   die "Error: Can't change directory - $!";
}

die "Error: Can't change directory!: $!" unless(chdir("/etc"));

The ternary operator

print(exists($hash{value}) ? 'There' : 'Missing',"\n");

The warn function

chdir('/etc') or warn "Can't change directory";

The die function

chdir('/etc') or die "Can't change directory";

Errors within modules

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;

sub function {
   warn "Error in module!";
}
1;

use T;
function();

The carp function

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;

sub function {
   carp "Error in module!";
}
1;

use T;
function();

The cluck function

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp qw(cluck);

sub function {
   cluck "Error in module!";
}
1;

use T;
function();

The croak Function

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;

sub function {
   croak "Error in module!";
}
1;

use T;
function();

The confess function

package T;

require Exporter;
@ISA = qw/Exporter/;
@EXPORT = qw/function/;
use Carp;

sub function {
   confess "Error in module!";
}
1;

use T;
function();