User:Swapnil durgade/Perl Notes
Appearance
Perl Components
[edit | edit source]Variables
[edit | edit source]Example
- Define: $message = "Hello World\n";
- Access: print $message;
Array
[edit | edit source]Example
- Define: @days = ('Mon','Tue','Wed','Thu','Fri','Sat','Sun');
- Access: $days[0]
Hash
[edit | edit source]Example
- Define: %months = ('January' => 31,'November' => 30,'December' => 31);
- Access: print "Days in November:",$months{'November'},"\n";
Operators
[edit | edit source]$Sum = 4 + 5
Statements
[edit | edit source]if
Subroutines (Functions)
[edit | edit source]Modules
[edit | edit source]Strings
[edit | edit source]substr function
[edit | edit source]Uses
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
[edit | edit source]For 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