Perl documentation
linux perl hugo
Loops
- while loop
my $i = 0;
while($i < scalar @array) {
print $i, ": ", $array[$i];
$i++;
}
- until loop
my $i = 0;
until($i >= scalar @array) {
print $i, ": ", $array[$i];
$i++;
}
- C-style loop
for(my $i = 0; $i < scalar @array; $i++) {
print $i, ": ", $array[$i];
}
- foreach loop with arrays
foreach my $i ( 0 .. $#array ) {
print $i, ": ", $array[$i];
}
- foreach loop with hash
foreach my $key (sort keys %scientists) {
print $key, ": ", $scientists{$key};
}
Array functions
- pop: Extracts and returns the final element of the array.
- push: appends extra elements to the end of the array.
- shift: extracts and returns the first element of the array.
- unshift: inserts new elements at the beginning of the array.
File handles
- open file and read from it
my $f = "text.txt";
my $result = open(my $fh, "<", $f) || die "Couldn't open '".$f."' for reading because: ".$!;
while(my $line = <$fh>) {
# process $line...
}
- open file and write to it
my $f = "text.txt";
open(my $fh, ">", $f) || die "Couldn't open '".$f."' for writing because: ".$!;
print $fh2 "The eagles have left the nest";
Regular expressions
- Match operations using =~ m// in scalar context. =~ m//g indicates “group match”
my $string = "Hello world";
if($string =~ m/(\w+)\s+(\w+)/) {
print "success";
}
- Match operations using =~ m// in list context. =~ m//g indicates “group match”
my $string = "colourless green ideas sleep furiously";
my @matches = $string =~ m/(\w+)\s+((\w+)\s+(\w+))\s+(\w+)\s+(\w+)/;
print join ", ", map { "'".$_."'" } @matches;
#prints "'colourless', 'green ideas', 'green', 'ideas', 'sleep', 'furiously'"
- Substitution operations are performed using =~ s///. =~ s///g performs a global search
my $string = "Good morning world";
$string =~ s/world/Vietnam/;
print $string; # "Good morning Vietnam"
References
- Scalar reference
use warnings;
use strict;
my $x = 10;
my $xr = \$x;
# change $x via $xr
$$xr = $$xr * 2;
print("$x\n"); # 20
print("$$xr \n"); # 20
print("$xr\n"); # SCALAR(0x1d2e6e4)
- Array reference
use warnings;
use strict;
my @a = (1..5);
my $ar = \@a;
my $i = 0;
for(@$ar){
print("$ar->[$i++] \n");
}
- Hash reference
#!/usr/bin/perl
use warnings;
use strict;
my %months= ( Jan => 1,
Feb => 2,
Mar => 3,
Apr => 4,
May => 5,
Jun => 6,
Jul => 7,
Aug => 8,
Sep => 9,
Oct => 10,
Nov => 11,
Dec => 12);
my $monthr = \%months;
for(keys %$monthr){
print("$_ = $monthr->{$_}\n");
}
- Command line read file and process
- -p makes Perl loop over the incoming data and print it out once you’ve finished fiddling with it
cat test | perl -p -e 's/(.*):(.*)/$2:$1/'
- system commands in perl
system("net use ${drive} \\\\${server}\\${remote_drv_ltr}\$ ${passwd} /USER:${domain}\\${login}");
perl -nwl -e '(/N(\s|_)2118\D/i or /(N)2118\D/i) and (/.aep\z/i) and print "$ARGV => $_" ;' 3dlist/*.txt firesafe_hdd/*.txt svnlist/*.list