Perl documentation


linux perl hugo

Loops

  1. while loop
    my $i = 0;
    while($i < scalar @array) {
    	print $i, ": ", $array[$i];
    	$i++;
    	}
  1. until loop
    my $i = 0;
    until($i >= scalar @array) {
    	print $i, ": ", $array[$i];
    	$i++;
    	}
  1. C-style loop
    for(my $i = 0; $i < scalar @array; $i++) {
    	print $i, ": ", $array[$i];
    	}
  1. foreach loop with arrays
    foreach my $i ( 0 .. $#array ) {
    	print $i, ": ", $array[$i];
    }
  1. foreach loop with hash
    foreach my $key (sort keys %scientists) {
    	print $key, ": ", $scientists{$key};
    }

Array functions

File handles

  1. 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...
    	}
  1. 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

    my $string = "Hello world";
    if($string =~ m/(\w+)\s+(\w+)/) {
    	print "success";
    }
    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'"
    my $string = "Good morning world";
    $string =~ s/world/Vietnam/;
    print $string; # "Good morning Vietnam"

References

  1. 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)
  1. Array reference
    use warnings;
    use strict;
    my @a = (1..5);
    my $ar = \@a;
     
    my $i = 0;
    for(@$ar){
        print("$ar->[$i++] \n");
    }
  1. 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");
    } 
    cat test | perl -p -e 's/(.*):(.*)/$2:$1/'
    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