5% assure discount from here only

Perl Tips and Tricks

On this page, you will find some PERL Tips and Tricks which can reduce the length and increase the performance of your PERL program. So Happy Programming.


Operators Tricks


(1) The operators ++ and unary - works on numbers and strings both.

my $a = "a";
print -$a."\n";
#prints -a



print ++$a;
#prints -b



my $b = 'z';
print ++$b;

#prints aa


(2) The quote operator (qw) magic:


my @item = ("food", "house" , "computer");


can be written as 


my @item = qw(food house computer);


(3) The index operator ($[)magic :

There also is $[ the variable which decides at which index an array starts. Default is 0 so an array is starting at 0. By setting



$[ = 1;
 
my @array = (1,2,3,4);
 

 print $array[0];
 #print 1


print $array[1];


#print 1 


(4) You can swap the numbers without using 3rd variable in 1 line.

my ($a, $b) = (5, 10);


#here $a = 5 and $b = 10


($a, $b) = ($b, $a);
#now $a = 10 and $b = 5 


(5) The -w option to check program for syntax errors:

perl -w myscript.pl

will tell you about the syntax error in your script if any.

(6) The boolean operator (||)




 $x = $a || $b;

# $x = $a, if $a is true.
# $x = $b, otherwise
 

This means one can write:

my $check = $a || $b || $c || 0;
 
to take the first true value from $a, $b and $c, or a default of 0 otherwise.

(7) To generate random number :


my $random = int(rand(10));


will generate an integer from 0 to 9




(8) To generate encrypted password :

my $passwd =crypt("lalit","bansal");
print $passwd; 

(9) To check the syntax of your script at the command line:-

perl -c yourscriptname.pl

(10) To count the number of times $checkword appears in $text :-

my $times = 0;
$times ++ while ($text =~ /\b $checkword \b/gx));

print $times;


(11) To look up the documentation of a perl module (installed on your system) at the command line:-

perldoc modulename

for e.g.
perldoc CGI


(12) To lookup for List of Installed perl module:-

instmodsh <option>
 
options are 
 
l = List all installed modules
m = Select a module 
q = quit


1 comment:

  1. Printing $^O prints which OS we are currently running in..

    print $^O

    ReplyDelete