Pages

Tuesday, November 6, 2012

Perl - Tips and Tricks


Here are some Perl info I found useful while coding and deemed fit to be shared.

####
a =~ s/^\s+//; # strip white space from the beginning
a =~ s/\s+$//; # strip white space from the end

###
Use "eq" (as well as lt, gt, ne, ge, le, cmp) for string matching. The operators "==" (as well as <, >, !=, >=, <=, <=>) for numeric matching.

###
Use 'last' to break from the loop. Break keyword which is used in C/C++ doesn't work in perl.

###
$line =~ s/\s+/ /g; will collapse multiple whitespaces into a single whitespace.

###
unlink("filename") is ued for deleting a file.

###
To open a file for reading as input, you can use -
open (MYFILE1, "<in.txt") or die "an error occured: $!";
To open file for writing output + appending, use
open (MYFILE2, "+>>out.txt") or die "an error occured: $!";

###
Remember to close the file you opened by using - close(MYFILE);

###
You can make an HTML file as output by using
$body = "<html> <head> </head>";
$body = $body."<table><tr><td> Test </td></tr></table>";
$body = $body."</html>";
print MYHTML $body;

###
to check the version of perl install - perl -v

###
to install new modules which are required by some scripts, you can download it from command line.
Eg, to install GD(Graphics) module,
perl -MCPAN -e shell (you will need to answer few questions before proceeding. Just put it to default if you don't understand the meaning)
install GD

###
to use graphics, you need the CGI module. To write an image in a file, first open the file and change to binmode. eg -
open (PIC, "+>>test.png") or die "an error occured: $!";
binmode PIC;
print PIC $data->png;

###
to print image in html file
$body=<img src=abc.png">;
print HANDLE $body;

No comments:

Post a Comment