Perl one liners

This list will grow over time - its also fun to know more how to sling around lists and use dereferences to create one-liners.

Perldoc

perldoc -f <function>
perldoc Data::Dumper

Deferences:

No matter how crazy looking the variable, to dereference, wrap the variable ref in {} then prepend with $ @ % for scalar/array/hash.

${$self->{scalarref}}   ${$self->{arrayref}}       None
@{$self->{arrayref}}   ${$self->{arrayref}}[1]     Brackets
%{$self->{hashref}}   ${$self->{arrayref}}{1}      Braces

Find and return the max value from a list (array):

sort returns an array (list) which is then assigned to an anonymous array [] , then dereferenced @{}
The pop function expects an array and pop sort @c does not work..

$ perl -e '@c=(1,3,7,19,17); printf "%s\n", pop @{[sort {$a <=> $b} @c]}' 
19

Uniq an array

From http://www.perlmonks.org/?node_id=280658

# create
@a = qw( 1 4 4 2 3 5 2 5 );

# uniq
@a = keys %{ { map { $_ => 1 } @a } };

# sort uniq
@a = sort keys %{ { map { $_ => 1 } @a } };

printf "$_\n" foreach (@a);

Decimal to Hex

% echo 255 255 85 | perl -lane 'printf "%s\n", uc(sprintf "#%02x%02x%02x", $F[0], $F[1], $F[2])'
#FFFF55

Catpure and replace

Capture, transform and replace some text.

% echo 'Please uppercase this (in the parens only("these letters") only)' |
perl -lne 'print; s/([ewy])\(("[^"]+")(?{$m=uc($2)})/$1\($m/; print'

Please uppercase this (in the parens only("these letters") only)
Please uppercase this (in the parens only("THESE LETTERS") only)

Subroutine - what is my name?

Use the caller function

#!/usr/bin/perl
sub woofer { 
    $sub_name = (caller(0))[3];
    printf "Subroutine is $sub_name and the first arg was \"$_[0]\"\n";
};
woofer("the sub says boom!");

Will print out:

Subroutine is main::woofer and the first arg was "the sub says boom!"

Perl debugger

Real notes are here: Perldoc - perldebtut These are the ones I use the most... full list of Perl debug commands

From the perldoc summary: We've seen how to encourage good coding practices with use strict and -w. We can run the perl debugger perl -d scriptname to inspect your data from within the perl debugger with the p and x commands. You can walk through your code, set breakpoints with b and step through that code with s or n, continue with c and return from a sub with r. Fairly intuitive stuff when you get down to it.

Debugging basics

Start up a debugging session

perl -d some/path/to/perl/script_that_does_cool_stuff

Breakpoint in your code (put in your file before starting debugger)

$DB::single=1
[..]
$DB::single=2
[..]
$DB::single=4

Advance to code breakpoint

c

single step through code

s

next

n

print out a variable

p

Dumper a variable - x

x

Published on in