User:Swapnil durgade/Perl Notes
Perl Components
editVariables
editExample
- Define: $message = "Hello World\n";
- Access: print $message;
Array
editExample
- Define: @days = ('Mon','Tue','Wed','Thu','Fri','Sat','Sun');
- Access: $days[0]
Hash
editExample
- Define: %months = ('January' => 31,'November' => 30,'December' => 31);
- Access: print "Days in November:",$months{'November'},"\n";
Operators
edit$Sum = 4 + 5
Statements
editif
Subroutines (Functions)
editModules
editStrings
editsubstr function
editUses
1. get subset of string 2. Replace subset of string with new string.
Syntax
$value = substr($string, $offset, $count); $value = substr($string, $offset);
substr($string, $offset, $count) = $newstring; substr($string, $offset, $count, $newstring); # same as previous substr($string, $offset) = $newtail;
E.g.
$string = 'abcd1234'; $subs = substr($string,4); print $subs; Output: 1234
$string = 'abcd1234'; substr($string,0,4)="pqrs"; print $string;
Output: pqrs1234
# substitute "at" for "is", restricted to first five characters substr($string, 0, 5) =~ s/is/at/g;
unpack function
editFor positioning, use lowercase "x" with a count to skip forward some number of bytes, an uppercase "X" with a count to skip backward some number of bytes, and an "@" to skip to an absolute byte offset within the record.
# extract column with unpack $a = "To be or not to be"; $b = unpack("x6 A6", $a); # skip 6, grab 6 print $b; or not
($b, $c) = unpack("x6 A2 X5 A2", $a); # forward 6, grab 2; backward 5, grab 2 print "$b\n$c\n"; or be