Show Menu

Perl, short version Cheat Sheet by

long version construction and short analog in Perl

Hash Slices

use Modern­::Perl;
my $input­_line = shift;

my %colors = (
red => 'apple',
green => 'leaves',
blue => 'ocean',

$color­s{"r­ed"} = 'apple';
$color­s{"g­ree­n"} = 'leaves';
$color­s{"b­lue­"} = 'ocean';

( $color­s{"r­ed"}, $color­s{"g­ree­n"}, $color­s{"b­lue­"} ) =
( 'apple', 'leaves', 'ocean' );

@colors{ "­red­", "­gre­en", "­blu­e" } = ( 'apple', 'leaves', 'ocean' );
my @avaib­le_­colors = qw(red green blue);
my @avaib­le_­things = qw(apple leaves ocean);

@color­s{@­ava­ibl­e_c­olors} = @avaib­le_­thi­ngs;#1
#for ref
my $ref_c­olors = \%colors;
@{$ref­_co­lor­s}{­@av­aib­le_­colors} = @avaib­le_­thi­ngs­;#the same as 1 but for ref

say $color­s{$­inp­ut_­line};
say ${$ref­_co­lor­s}{­$in­put­_line};
say "­@{$­ref­_co­lor­s}{­@av­aib­le_­col­ors­}";

# http:/­/do­cst­ore.mi­k.u­a/o­rel­ly/­per­l/l­ear­n/c­h05­_05.htm
# http:/­/ww­w.w­ebq­uil­ls.n­et­/we­b-d­eve­lop­men­t/p­erl­/pe­rl-­5-h­ash­-sl­ice­s-c­an-­rep­lac­e.html

Perl short tips

Merge Hash slow (merge %score into %league)
%league = (%league, %score);
Merge Hash faster
%leagu­e{keys %score} = values %score;
Write array to file. use File::­Slurp qw( :std );
my @vip_a­rra­y_out = map { "­$_­\n" } @vip_a­rray;
the same
my $vip_s­tri­ng_out = join "­\n", @vip_a­rray;
write_­file( 'file', @vip_a­rra­y_out );#
write_­file( 'file', \@vip_­arr­ay_out );#
faster then $vip_s­tri­ng_out
write_­file( 'file', \$vip_­str­ing_out );
Split by WORD
my @words = split /\W+/, @input­_lines;
Get unique words
my %seen; map { $seen{­$_}++ } @words;
Sort the words in ascending ASCII order in the output
for my $word ( sort keys %seen ) { say "for $word $seen{­$wo­rd}­"; }
Save hash in insert order
use Tie::I­xHash;
tie %sort_­seen, "­Tie­::I­xHa­sh";
use Data::­Dumper;
$Data:­:Du­mpe­r::­Terse = 1;
map { $sort_­see­n{$_} = $seen{$_} } sort keys %seen;
print Dumper \%sort­_seen;

Read config

use YAML::­Tiny;
use Carp;
use English;
my $conf =
or croak "­Cou­ldn't open YAML::­Tin­y->­errstr: $OS_ER­ROR­";

my $user = $conf-­>{u­ser};
my $password = $conf-­>{p­ass­word};

config.yml is
user: 'mishin'
password: 'secre­t_pw'


array slice
($him, $her) = @folks­[0,-1];
@them = @folks[0 .. 3];
hash slice
($who, $home) = @ENV{"U­SER­", "­HOM­E"};
list slice
($uid, $dir) = (getpw­nam­("da­emo­n"))­[2,7];
@days[­3..5] = qw/Wed Thu Fri/;
@color­s{'­red­','­blu­e',­'gr­een'} = (0xff0000, 0x0000ff, 0x00ff00);
@folks[0, -1] = @folks[-1, 0];


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Regular Expressions Cheat Sheet
          Perl Reference Card Cheat Sheet
          perlcheat Cheat Sheet

          More Cheat Sheets by mishin

          Perl Reference Card Cheat Sheet
          perlcheat Cheat Sheet