Can't remember how to do that thing in Perl? Neither can I, so I write it down. I hope you find this helpful.
- "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"
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"
});
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'" });
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]";
}
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;
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
use Perl6::Slurp;
# For text content:
my $file_data = slurp '/etc/passwd';
# For binary:
my $file_data = slurp '/etc/passwd', { raw => 1 };
open( my $fh, '<', '/etc/passwd' )
or die "Cannot open passwd [$!]";
my $file_data = do { local $/; <$fh> };
close $fh;
Foreach will read in the whole file, consuming ram, but while consumes the file line by line.
while ( my $line = <> ) {
chomp line;
....
$results = qx{ ls -l };
OR
open( my $fh, '-|', 'ls -l' ) or die "Cannot open ls [$!]";
my $results = do { local $/; <$fh> };
close $fh;
perl -pi -e 's///g' <file>
# Treat file as one string and match over multiple lines
perl -pi -0 -e 's///msg' <file>
perl -pi -e 's/\r\n/\n/g' input.file
( my $new_var = $original ) =~ s/teh/the/g ;
( my $match ) = $original =~ m/(kept)/;
perl -MFile::Find=find -MFile::Spec::Functions -Tlwe \
'find { wanted => sub { print canonpath $_ if /\.pm\z/ }, \
no_chdir => 1 }, @INC'
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
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;
print '-' x 80; # print row of 80 dashes
Consult CPAN's Task::Kensho
perl -MText::Markdown -E'say Text::Markdown->new->markdown( join "", <> )' index.md
To access Satellite and Cobbler API's use XMLRPC::Lite
$server = XMLRPC::Lite->new( proxy => $server_url);
$token = $server->login( $username, $password )->result();
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;
}
}
my $system_id = $server->new_system( $token )->result()
or die "Could not create new 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, [$!]";
The mtime attribute form get_systems is in epoch seconds.
$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, [$!]";
my $server = XMLRPC::Lite->new( proxy => $server_url );
my $token = $server->call( 'auth.login', $username, $password )->result();
my $systems = $server->call( 'system.listSystems', $token )->result;
$rec->{name}
$rec->{id} # Note that id and SystemId are equal in the API.
$rec->{last_checkin} # in form YYYMMDDTHH:MM:SS
# @delete is an array of id or SystemId from returned systems.
my $err = $server->call(
'system.deleteSystems', $token, \@delete ) unless $argref->{dryrun};
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.
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.