Perl, short version Cheat Sheet

A Programming › Perl cheat sheet in English by mishin

long version construction and short analog in Perl

18,549 views 5,874 downloads 16 Jul 2012 History
4.3 avg · 1 rating

Hash Slices

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

my %colors = (
red => '­app­le',
green => '­lea­ves­',
blue => '­oce­an',
);

$color­s{"r­ed"} = '­app­le';
$color­s{"g­ree­n"} = '­lea­ves­';
$color­s{"b­lue­"} = '­oce­an';

( $color­s{"r­ed"}, $color­s{"g­ree­n"}, $color­s{"b­lue­"} ) =
( '­app­le', '­lea­ves­', '­oce­an' );

@colors{ "­red­", "­gre­en", "­blu­e" } = ( '­app­le', '­lea­ves­', '­oce­an' );
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;
slow
write_­file( '­fil­e', @vip_a­rra­y_out );#
faster
write_­file( '­fil­e', \@vip_­arr­ay_out );#
faster then $vip_s­tri­ng_out
write_­file( '­fil­e', \$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 =
YAML::­Tin­y::­Loa­dFi­le(­'­con­fig.ym­l')
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: '­mis­hin­'
password: '­sec­ret­_pw­'

Slices

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{'r­ed',­'­blu­e','g­ree­n'} = (0xff0000, 0x0000ff, 0x00ff00);
@folks[0, -1] = @folks[-1, 0];

Badges

Nice Cheat Sheet Good Cheat Sheet

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.