"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

June 20, 2010

Learning Perl & Linux

Yep I am back to learning Perl. I worked in Perl long back. Posting sample programs from my notes I took earlier...
Perl (Practical Extraction and Report Language) - Interpreted Language. They are not compiled. Programs are directly executed by the CPU. More Details in link

Linux Commands
  • rm -i filename - remove file
  • mv test test1 - rename file
  • cp a.pl b.cp - copy file
  • chmod - change the mode
  • logname- print name of logged in user
  • df - disk free, disk space usage
  • grep - globally search for regular expression
  • grep print test1.pl - search for print word in test1.pl file
  • head -15 printdata.pl - list 15 lines of the file
Example 1 - Multiplication of Two Numbers
I learnt basic vi editor commands as well. :wq - save and quit, :i insert, :q - quit without save, vi filename (open / create file if it does not exists)

#!/usr/bin/perl
print 'Multiplication';
print 'A Number';
$aNumber = <>;
print 'B Number';
$bNumber = <>;
$result = $aNumber*$bNumber;
print 'result = ';
print $result;

Example 2 - Conditional Operators in Perl
#!/usr/bin/perl
$grade = <>;
if($grade < 8)
{
    print " < 8";
}
else
{
    print " > 8";
};
Example 3 - Dealing with text - strings
  • ne - not equal
  • ge - greater or equal
  • gt - greater than
  • le - less or equal
  • lt - less than
  • eq - equal
#!/usr/bin/perl
print 'program begin \n';
if ('a' eq 'a')
{
    print 'R1 - a is equal';
}
else
{
    print 'R1 - a is not equal to a ';
};
if ('a' lt 'b')
{
    print 'R2 - a less than b';
}
else
{
    print 'R2 - a is greater than b';
};
print '\n end of program';
<>;

Example 4 - Arrays in Perl
#!/usr/bin/perl
@array = (1,2,3,4);
$number = 0;
foreach $number (@array)
{
    print "$number\n"
}
<>;

More Reads
50 Most Frequently Used UNIX / Linux Commands (With Examples)

In Linux Terminal
vi ginfo.sh
Insert below contents
echo "Hello" $USER
echo "Today is ";date
exit 0
Save the file
:wq
Provide permissions to execute
chmod 755 ginfo.sh
Run the below command
./ginfo.sh

Thanks to Sarabjit for helping me learn below commands

grep "searchkeyword" filenamecontains* > /tmp/test.op
vi /tmp/test.op
find -name "filenamecontains*" -exec grep "searchkeyword" {} \; > /tmp/test.op
find -name "filenamecontains*" -mmin -60 -exec grep "filenamecontains*" {} \; > /tmp/test.op (Modified last 60 mins)
Happy Learning !!

No comments: