Tips in Perl

In this post, I will list some minor but might be a bit tricky tips here.

Tips One:

sub test{
my ($key) = @_;
print $key;
}

test(“I am key”);

Output:

I am key

===============

sub test{
my $key = @_;
print $key;
}

test(“I am key”);

Output:

1

==============

I think the reason here is that, Perl passes argument list as an array into routine but not a scalar. So my($key) it is a correct way to reference a list context however my $key will just wrongly refer to a scalar context.

 

Tips Two:

system(“perl -pi -e \”print unless /” . “$key/\” abc.txt”);

Then it will fail ONLY on Windows Platform as it will complain that “Can’t do inplace edit without backup”.

You need to add .bak (no necessary ending with bak, you can use .abc or other names) to create a backup firstly.

And ensure that even you have .bak in the command, you still have to ensure that no file handler is opening abc.txt or it will complain that the file is On Edit status.

 

Tips Three:

If you want to add a new file in the heading of a file, you can do as below:

open IN, ‘<‘, $template or die “can’t open $template: $!”;
open OUT, ‘>’, $initiatedtmpl or die “can’t open $initiatedtmpl: $!”;
print OUT “spool $report \n”;# here I want to add as the first line.
while (<IN>) {
print OUT “$_ “;
#debugPrint $_;
}
close OUT;

 

Tip Four:

You have to add one line as the last line in a file in a fast way:

tie @lines, Tie::File, $cons or die “can’t tie $cons: $!”;
push @lines, “$key”;
untie @lines;

 

Tips Five:

You have a string as below:

I am Luohua and I love IT

I hope you will love that too

Let’s change the world.

Then you want to read it into a array as

array[0]=”I am Luohua and I love IT”;

array[1]=”I hope you will love that too”;

array[2]=”Let’s change the world.”;

Below is the one line script:

@SQLPLUS_REPORT = split /^/m, $content;

# ^ Match string start (or line, if /m is used)