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;

 

Replace Strings in Multiple Files

“sed” command can be used for replacing strings in a file. For example, you can use the command below to replace “Apple” with “Orange” in fruits.txt file.

$ sed -i".bkp" -e "s/Apple/Orange/g" fruits.txt

Parameter “-i” makes the target file overwritten, but a backup is created by specifying a string (“.bkp” for this case) after “-i” whose filename has the string as suffix.

You can combine “xargs” and “find” command with “sed” to process multiple files at once. “find” is for searching files and “xargs” is for executing any commands using values from standard input as parameters. For example, you can use the command below to replace “Apple” with “Orange” in all files in current directory.

$ find . -maxdepth 1 -type f | xargs sed -i".bkp" -e "s/Apple/Orange/g"

Remove Old Files

You can use “find” command with “-exec” parameter to remove old files in UNIX system.

$ find <Directory> -maxdepth 1 -mtime +<Days> -exec rm -f {} \;

Please see the following for the meanings of each parameter.

<Directory> Specify a directory where the target files are located.
-maxdepth 1 Search files only in the given directory by setting “1”. Ignore the child directories.
-mtime +<Days>

Search files modified more than <Days> days ago.

 

-exec rm -f {} \; Execute “rm” command on the found files.

 

Merge Hashes

Javascript doesn’t have standard function to merger hashes. We can do it like below.

var hash1 = {'us': 'USD', 'jp': 'JPY'};
var hash2 = {'cn': 'CNY'};

for (var key in hash2) {
    hash1[key] = hash2[key];
}

 

Top