We have moved to www.dataGenX.net, Keep Learning with us.

Tuesday, March 20, 2012

Perl 1 liners : tips & tricks : Part -1

Typically there are cases, where one would not like to create a source file to check small programs. Such things can be tested by running them using "-e" option of the Perl. There are many other command line switches available and some of them have been listed below.

List of Perl's Command Line Switches  Switch Description

-e This option can be used to enter a Perl program directly in the command line. 
-p This option loops around your program and print it. 
-n This option too loops around your program. 
-l Automatically chomps the input line (basically gets rid of newline at the end). 
-a Autosplit mode with -n or -p option. 
-i Edit <> files in place. 
-d Runs the program in debug mode. 
-v Prints version and sub-version of the Perl binary. 
-w Enables the useful warnings. 
-W Enable all warnings. 
-X Disable all warnings. 

Below are some handy one-liners which should be useful to all Perl programmers.

1. Remove all blank lines from a file

perl -i -ne 'print unless /^$/' file_name

The -n flag causes Perl to assume a similar program.

while (<>) {
    print unless $_ =~ /^$/;

2. Print the number of empty lines in a file.

perl -lne '$a++ if /^$/; END {print $a}' file_name

The -l argument makes sure a newline gets added afterprinting out this number. The above program is interpreted as below.

while (<>) {
    $a++ if $_ =~ /^$/;

END { print $a; print "\n"; }

3. Find the total number of fields (words) in each line.

perl -alne 'print scalar @F' file_name

# or

perl -alne 'print ~~@F' file_name

The -a argument turns on field auto-splitting.This one-liner forces to evaluate the @F in scalar context, which inPerl means "the number of elements in @F." Therefore thisone-liner prints out the number of elements on each line.

4. Find the total number of fields (words) on all lines.

perl -alne '$t += @F; END { print $t }'

Here we just keep adding the number of fields on each line to the variable $t, and at the end we print it out. The result is number of words on all lines.

5. Generate and print the alphabet or numbers.

perl -le 'print a..z'
    #prints abcdefghijklmnopqrstuvwxyz
perl -le 'print 1..20'
    # prints 1234567891011121314151617181920

It actually becomes difficult to interpret the output because there is not field separator in the output. If one wishes to include whitespaces between the output numbers (or alphabets) then it may be assigned to an array variable and then printed, as given below.

perl -le '@F=A..Z; print "@F"'
    #prints A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
perl -le '@F=1..15; print "@F"'
    # prints 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

If one wants the alphabetical series as AA, AB and so on, the following trick can be used

perl -le '@F=A..AZ; print "@F"'
    # prints A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

It is also possible to change the field separator in the output by using the $, (the Output Field Separator built-in variable).

perl -le '$, = ","; print a..z'
    # prints a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z

6. Generate Random numbers.

perl -le '$,= "\n"; print map { ("890".."999")[rand 26] } 1..4'
    # prints 890
    #        907
    #        900
    #        914

In each iteration the code chooses a random number from the numbers between 890-999. When map is done iterating, it returns the generated list of numbers and prints it out.

7. Create an array of even or odd numbers.

perl -le '@even = grep {$_ % 2 == 0} 1..100; print "@even"'

The above code generates an array of odd numbers from 1 to99 (as 1, 3, 5, 7, 9, 11, ..., 99). It uses the grepfunction that evaluates the given code $_ % 2 == 1 for eachelement in the given list 1..100 and returns only theelements that had the code evaluate to true.

8. Find the length of the string.

perl -le 'print length "one-liners are great"'
     # prints 20

9. Find the number of elements in an array.

perl -le '@array = ("a".."z"); print ~~@array'
    # prints 26

10. Convert all text to uppercase, lowercase.

perl -nle 'print uc' file_name
    # prints file in uppercase.

perl -nle 'print lc' file_name
    # prints file in uppercase.

We will continue this session in next part. till then...

Enjoy the Simplicity.........

No comments :

Post a Comment