Skip to content

Latest commit

 

History

History
executable file
·
618 lines (379 loc) · 11.9 KB

cheatsheet.pod

File metadata and controls

executable file
·
618 lines (379 loc) · 11.9 KB

Perl cheatsheet

Can't remember how to do that thing in Perl? Neither can I, so I write it down. I hope you find this helpful.

Table of contents

"Subroutines"
"Named parameters to subroutines."
"With default values"
"Return named params from a subroutine"
"Objects"
"Making an object"
"Making an inside out object"
"Input Output"
"Slurp a file the Perl 6 way"
"Slurp a file the old way"
"Read from stdin"
"Slurp from stdout of a command"
"In the shell"
"Shell search and replace"
"Remove DOS format carriage return characters."
"Matching and search and replace"
"Search and replace, keep original and assign change to new variable."
"Match and store match in a single line"
"Debugging"
"List available modules"
"Deparse Perl code"
"Shelling out"
"Checking the return of a system call"
"Repeat operator"
"What module should I use?"
"Markdown"
"Quicky test your markdown"
"Satellite snippets, including Cobbler"
"Connect to Cobbler API"
"Dump Cobbler systems"
"Create Cobbler system"
"Update Cobbler system"
"How to purge a Cobbler system"
"Delete Cobbler system"
"Connect to Satellite API"
"List Satellite systems"
"Access date from systems"
"Delete Satellite systems"
"Time and dates"
"Difference or two date stamps in days"
"Further reading"
"Licence"

Subroutines

Named parameters to subroutines.

    sub named_params_example {
       my ( $arg ) = @_;
       # Use my ( $self, $arg ) = @_; if you are in object land.
    
       say $arg->{one};
       say $arg->{two};
    }
    
    named_params_example({
       one => "First argument",
       two => "Second argument"
    });
    
    # In object land
    named_params_example(
    $self, {
       one => "First argument",
       two => "Second argument"
    });

With default values

    sub named_params_with_defaults {
       my ( $arg ) = @_;
       # Use my ( $self, $arg ) = @_; if you are in object land.
       
       # Set defaults
       #         If option given      Use options   Else
       my $one = exists $arg->{one} ? $arg->{one} : "default1";
       my $two = exists $arg->{two} ? $arg->{two} : "default2";
    
    }
    
    named_params_with_defaults({ one => "override arg 'one'" });

Return named params from a subroutine

    sub foo {
       my $clause = 'This is a clause';
       my @param = qw/ one two thee /;
    
       return ({
          clause => $clause,
          params => \@param
       });
    }
    
    my $r = foo();
    
    say "clause = [$r->{clause}]";
    for my $p ( @{ $r->{params} } ) {
       say "param = [$p]";
    }

Objects

Making an object

Consider using object packages like Moo for larger projects, but by hand:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use feature 'say';
    
    my $o = Neil->new({ foo => 'bar', time => '11:30'});
    
    $o->dump_args;
    
    #######
    package Neil;
    
    use strict;
    use warnings;
    
    sub new {
       my ( $class, $arg ) = @_;
       my $self = bless $arg, $class;
    
       return $self;
    }
    
    sub dump_args {
       my $self = shift;
       say 'arg foo is '. $self->{foo};
       say 'arg time is '. $self->{time};
    }
    
    1;

Making an inside out object

Consider using object packages like for larger projects, but by hand:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use Test::More;
    
    my $vm_swappiness = Sysctl->new({ variable => 'vm.swappiness' });
    
    is( $vm_swappiness->get, 60, "vm.swappiness == 60" );
    ok( $vm_swappiness->set( 67 ), "set vm.swappiness = 67" );
    is( $vm_swappiness->get, 67, "vm.swappiness == 67" );
    ok( $vm_swappiness->set( 60 ), "set vm.swappiness = 60" );
    is( $vm_swappiness->get, 60, "vm.swappiness == 60" );
    
    done_testing;
    
    #
    #
    #
    package Sysctl;
    
    use strict;
    use warnings;
    use POSIX qw( WIFEXITED );
    use Carp;
    
    my $sysctl_cmd = '/sbin/sysctl';
    my %sysctl_var;
    
    sub new {
       my ( $class, $arg_ref ) = @_;
       my $self = bless {}, $class;
    
       $sysctl_cmd = '/sbin/sysctl';
    
       $sysctl_var{$self} = $arg_ref->{variable}
          || croak q{
    Error Setting variable => is required when contructing new class. e.g.
    Sysctl->new({ variable => 'vm.swappiness' }); };
    
       return $self;
    }
    
    sub get {
       my $self = shift;
       my ( $sysctl_value )
          = qx{ $sysctl_cmd $sysctl_var{$self} } =~ m/= \s+ (\S+) /mxs;
       return $sysctl_value;
    }
    
    sub set {
       my ( $self, $value ) = @_;
    
       return WIFEXITED(
          ( system "$sysctl_cmd -w $sysctl_var{$self}='$value'" ) >> 8
       );
    }
    
    sub DESTROY {
        my $dead_body = $_[0];
        delete $sysctl_var{$dead_body};
        my $super = $dead_body->can("SUPER::DESTROY");
        goto &$super if $super;
    }
    
    1;

Or use Class::InsideOut

Input Output

Slurp a file the Perl 6 way

    use Perl6::Slurp;
    
    # For text content:
    my $file_data = slurp '/etc/passwd';
    
    # For binary:
    my $file_data = slurp '/etc/passwd', { raw => 1 };

Slurp a file the old way

    open( my $fh, '<', '/etc/passwd' )
       or die "Cannot open passwd [$!]";
    my $file_data = do { local $/; <$fh> };
    close $fh;

Read from stdin

Foreach will read in the whole file, consuming ram, but while consumes the file line by line.

    while ( my $line = <> ) {
       chomp line;
       ....

Slurp from stdout of a command

    $results = qx{ ls -l };
    
    OR
    
    open( my $fh, '-|', 'ls -l' ) or die "Cannot open ls [$!]";
    my $results = do { local $/; <$fh> };
    close $fh;

In the shell

Shell search and replace

    perl -pi -e 's///g' <file>
    
    # Treat file as one string and match over multiple lines
    
    perl -pi -0 -e 's///msg' <file>

Remove DOS format carriage return characters.

    perl -pi -e 's/\r\n/\n/g' input.file

Matching and search and replace

Search and replace, keep original and assign change to new variable.

    ( my $new_var = $original ) =~ s/teh/the/g ;

Match and store match in a single line

    ( my $match ) = $original =~ m/(kept)/;

Debugging

List available modules

    perl -MFile::Find=find -MFile::Spec::Functions -Tlwe \
       'find { wanted => sub { print canonpath $_ if /\.pm\z/ }, \
       no_chdir => 1 }, @INC'

Deparse Perl code

Useful for seeing how Perl sees your code.

    perl -MO=Deparse,-p -e \
       'mkdir "foo" unless -e "foo" or die "Cannot create foo: $!"'
    
    (((-e 'foo') or die("Cannot create foo: $!")) or mkdir('foo'));
    -e syntax OK

Shelling out

Checking the return of a system call

    use POSIX qw/ WIFEXITED /;
    use Test::More;
    use feature 'say';
    
    sub return_false {
       return WIFEXITED( (system "/bin/false" ) >> 8 );
    }
    
    sub return_true {
       return WIFEXITED( (system "/bin/true" ) >> 8 );
    }
    
    my $ret = return_false();
    say "returned [$ret]";
    ok( ! return_false(), 'This should return false' );
    
    $ret = return_true();
    say "returned [$ret]";
    ok( return_true(),    'This should return true' );
    
    done_testing;

Repeat operator

    print '-' x 80;     # print row of 80 dashes

What module should I use?

Consult CPAN's Task::Kensho

Markdown

Quicky test your markdown

    perl -MText::Markdown -E'say Text::Markdown->new->markdown( join "", <> )' index.md

Satellite snippets, including Cobbler

To access Satellite and Cobbler API's use XMLRPC::Lite

Connect to Cobbler API

    $server = XMLRPC::Lite->new( proxy => $server_url);
    $token = $server->login( $username, $password )->result();

Dump Cobbler systems

    sub dump_systems {
      my $results;
      my $systems = $server->get_systems->result();
      if ( $opts{hostname} ) {   
          foreach my $s ( @{$systems} ) {
              push @{$results}, $s if ( $s->{hostname} eq $opts{hostname} );
          }
          return $results;
      }   
      else {   
          return $systems;
      }   
    }
     

Create Cobbler system

    my $system_id = $server->new_system( $token )->result()
      or die "Could not create new system, [$!]";

Update Cobbler system

    $server->modify_system(
       $system_id, 'name', $opts{profile_name}, $token )->result()
       or die "Could not set name [$opts{profile_name}], [$!]";
    
    $server->modify_system(
       $system_id, 'kernel_options', "$opts{append}", $token)->result()
       or die "Could not set append, [$!]";
    
    $server->modify_system(
       $system_id, 'server', "$proxy{$sitename}.$domain", $token)->result()
       or die "Could not set server, [$!]";

How to purge a Cobbler system

The mtime attribute form get_systems is in epoch seconds.

Delete Cobbler system

    $server->remove_system($opts{profile_name}, $token )->result()
      or  die "Could not delete system [$opts{profile_name}], [$!]";
    
    $server->sync($token )->result()
      or die "Could not sync new system, [$!]";

Connect to Satellite API

    my $server  = XMLRPC::Lite->new( proxy => $server_url );
    my $token   = $server->call( 'auth.login', $username, $password )->result();

List Satellite systems

    my $systems = $server->call( 'system.listSystems', $token )->result;

Access date from systems

    $rec->{name}
    $rec->{id} # Note that id and SystemId are equal in the API.
    $rec->{last_checkin} # in form YYYMMDDTHH:MM:SS

Delete Satellite systems

    # @delete is an array of id or SystemId from returned systems.
    my $err = $server->call(
       'system.deleteSystems', $token, \@delete ) unless $argref->{dryrun};

Time and dates

Difference or two date stamps in days

    use Time::Piece;
    my $date1 = Time::Piece->strptime( $args{date}, "%Y-%m-%dT%H:%M:%S" );
    my $date2 = Time::Piece->strptime( $args{date}, "%Y-%m-%dT%H:%M:%S" );
    
    my $diff = $date1 - $date2;
    my $days = $diff->days

Useful in converting datastamps to time objects. Can also diff in minues. See module documentation for more info.

Further reading

Perl one liners

Licence

The MIT License (MIT)

Copyright (c) 2014 Neil H Watson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.