Exclude Line Number from die() Message

In Perl, we sometimes catch die() using eval as an exception handling and use the string given as the parameter of die() in it, like in the example below.

$ vim die_test
#!/usr/bin/perl

eval {
    die "Exception occurred";
};
if ($@) {
    print $@;
}

This script will display the below output on console.

$ ./die_test
Exception occurred at die_test line 4.

This output is fine as long as you use it for error message. But, if you want to use the string for other process, “at die_test line 4” would be an obstacle. To exclude the line number, you can simply add line break (\n) at the end of the string.

#!/usr/bin/perl

eval {
    die "Exception occurred\n";
};
if ($@) {
    print $@;
}
$ ./die_test
Exception occurred

Get and Set Environment Variable

In Perl, environment variables for the OS are stored in “%ENV” hash. So, for example, environment variable “PATH” can be gotten like this.

my $path = $ENV{"PATH"};

Setting environment variable is also easy. You can just add an element to %ENV.

$ENV{"PATH"} = $path;

 

Count Item in an Array

To get the number of items in an array, you can evaluate the array as scalar context.

my @array = ("Apple", "Orange", "Tomato");

my $count = @array;
print $count;

Also scalar method can be used. This way seems more simple.

print scalar(@array);

 

Top