Neat Perl Tricks
By: Keith Watanabe
Published On: 6-30-2008
Using qw for an array ref:
[qw(item1 item2 item3 item4)];Extracting parts of a split list
my ($item1, $item2, $item3) = (split(/s+/, $str))[2,4,5];Converting An Array To Key-Value Pairs For A Hash
my @list = qw(key1 val1 key2 val2 key3 val3 key4 val4);my %h = %{+{@list}};
Calling a function inside of a quoted element
Very useful when you don't want to end a quote or heredoc.my $var = "hello @{[getName()]}n";
Checking if the correct number of parameters are passed into a subroutine
sub func {die unless @_ == 4;
}
Using A Lookup Table To Quickly Validate If Arguments Exist
Good for checking input.
sub validate {
my %args = (arg1 => 1, arg2 => 1, arg3 => 1, arg4 => 1);
return exists $args{$_};
}
Converting a subroutine's arrayref argument to an array
some_func("arg1", "arg2", ['item1', ['item2'], ['item3'], ['item4']);sub some_func {
my $arg1 = shift;
my $arg2 = shift;
my @items = @{shift()};
print "$_n" for @items;
}
Dynamic Subroutines With Hashrefs
Nice technique when you want to create callbacks and require that the function calls are a little dynamic (for instance, when you don't know what function you might need to call).my $h = { progname => 'some_func' };
eval "$h->{progname}('David')";
sub some_func {
print "Hello $_[0]n";
}
Getting Local Time in Epoch Seconds
use Time::Local;my $sec = timelocal( (localtime)[0..5] );
Efficient File Slurping
open (FILE, $dir) || die $!;my $file = do { local $/; <FILE> };
close (FILE);
Getting All Files in A Directory
opendir( DIR, $dir ) || die $!;my @segdirs = grep { !/^./ } readdir( DIR );
closedir( DIR );
Better Inheritance in Perl
use base(Path::MyClass);Creating A Basic Constructor
sub new {my ($class, %args) = @_;
my $self = {};
bless $self, ref $class || $class;
}
Creating A Singleton Instance
Using the constructor from above:sub instance {
my $class = shift;
strict 'refs';
my $instance = ${"$class::_instance"};
defined $$instance ? $$instance : ( $$instance = $class->new( @_ ) );
}
Post Comment
Trackbacks: (Trackback URL)
No Comments Posted Yet
