Perl Basics

Debugging

 -w option
Debugger
perl -w -d my.pl  # with perl
perl -w -d -e "1;"    # no code

Variables

Perl has 3 kinds of variables:
  • scalar
  • array
  • hash 
Parameters can only be scalar. To pass other kind, it needs to be converted to a scalar (using reference).
scalar
$a=5; 
local $b='hello';
Array
my @num=(1,2,3);
my @str=("hello", "one");
my @mixed=("hello",1,2);
print $mixed[1];

@colors = ("red","green","blue");
($a, @somecolors) = @colors; # $a is first item; @somecolors are rest of @colors
(@somecolors, $a) = @colors; # @somecolors are @colors; $a is undefined
Hash
%fruit = (
       one => "apple",
       two => "orange",
       three => "peach"
       );

@key = keys %fruit;
@value = values %fruit;
print "$fruit{one} $key[1] $value[1]\n";

#hash of hashes
%HoH = (
  t1 => { a1 => "a1",
          a2 => "a2",},
  t2 => { b1 => "b1",
          b2 => "b2",},
);
print "$HoH{t1}{a2}\n";

Complex Data Type using Reference

# reference
$multiple = {
  m1 => { 
           onee => "app",
                  twoo => "ppa",
         },
         m2 => {
           test => "t",
    test2 => "y",
                },

};


print "$multiple->{m1}{onee} \n";

Conditionals

# if
if ( condition ){
  ...
}
elsif (condition ) {
  ...
}
else{
  ...
}

# unless
unless ( condition )
{
   ...
}

Loop

While
while (condition) { ... }
until (condition) { ... }
for
for ($i = 0; $i < 10; $i++)
{
   ...
}

for my $i ('a','b','c'){
  print $i;
}
foreach
foreach my $file (@mdfiles) 
{
   print "$file";
}

foreach (@array) {
   print "$_\n";
}

print $list[$_] foreach 0 .. $max;

foreach my $key (keys %hash) {
    print "The value of $key is $hash{$key}\n";
}

Operators

Numbers
 ==, !=, <, >, <=, >= 
Strings
 eq, ne, le, ge, lt, gt

Regular Expression

if (/tst/) { ... }         # true if $_ contains "tst"
if ($a =~ /hello/) { ... } # true if $a contains "hello"

s/a/b/;                    # replaces a with b in $_
$a =~ s/a/b/;              # replaces a with b in $a

External Commands

#1
$res = system("ls");

#2
my $exam=`mdadm --examine /dev/$dev 2>&1`; 

if ($? != 0){
   print "error\n";
}

Functions

sub setError($)
{
    $errorCode |= shift;
    return 1;
}
 

No comments: