Search This Blog

Tuesday 26 January 2016

Interesting and Useful Perl Operators/Commands/Operations

Declarations
my-for local variable declaration
# - Comment
@-Array
$-Scalar variable
eq- equals to operator for string operations
ne-not equals for string operators

Matching
=~ - contains or matches part of a string
ex:if($var=~/'$sometext'/)
{
}

!~ - doesnt contains or matches 
ex:
if($var=~/'$sometext'/)
{
}

~~  - to check if the variable is in an array
ex: $ModelText ~~ @CompletedModels

Replace:
s/match/replace/g
ex: s/a/b/g - will replace all occurrences of a with b

Loop
foreach my $a(@AnArray)
{
    #like all other foreach loops
}

Opening a File
my $filepath = "<urpath>";
open(varFileHandler,$filepath);
#opens the file and stores it handler to varFileHandler variable
seek(varFileHandler,0,0);
#to move the file handler to point to first line, first character
close(varFileHandler);
#close file
Open File for writing
open JSONOut,">$FilePath" or die "cant open json to write";

Working with CSV files
declare CSV package at the top.
use Text::CSV;
install it using PPM-Perl Package Manager.
in cmd, type: ppm install Text-CSV

then get the csv separator.
my $csv = Text::CSV->new({ sep_char => ',' });
then, parse
$csv->parse($TempLine)
then, split it
my @fields = $csv->fields();

Some Common useful operations in text processing:
remove beginning and trailing white spaces: $TempVar =~ s/^\s+|\s+$//g
remove special chars like \r \n: chomp($TempVar);

Functions
ex:
sub PrintJsonAttrib
{
    #print $_[0].$_[1];
    print JSONOut "\"".$_[0]."\"".":"."\"".$_[1]."\"".","."\n";
}

i am using this function to print out the 1 and 2nd argument of my function.
$_ - contains the arguments. its like argv array in c.

No comments:

Post a Comment