Hash Slices
use Modern::Perl;
my $input_line = shift;
my %colors = (
red => 'apple',
green => 'leaves',
blue => 'ocean',
);
$colors{"red"} = 'apple';
$colors{"green"} = 'leaves';
$colors{"blue"} = 'ocean';
( $colors{"red"}, $colors{"green"}, $colors{"blue"} ) =
( 'apple', 'leaves', 'ocean' );
@colors{ "red", "green", "blue" } = ( 'apple', 'leaves', 'ocean' );
my @avaible_colors = qw(red green blue);
my @avaible_things = qw(apple leaves ocean);
@colors{@avaible_colors} = @avaible_things;#1
#for ref
my $ref_colors = \%colors;
@{$ref_colors}{@avaible_colors} = @avaible_things;#the same as 1 but for ref
say $colors{$input_line};
say ${$ref_colors}{$input_line};
say "@{$ref_colors}{@avaible_colors}";
# http://docstore.mik.ua/orelly/perl/learn/ch05_05.htm
# http://www.webquills.net/web-development/perl/perl-5-hash-slices-can-replace.html |
|
|
Perl short tips
Merge Hash slow (merge %score into %league) %league = (%league, %score);
|
Merge Hash faster %league{keys %score} = values %score;
|
Write array to file. use File::Slurp qw( :std ); my @vip_array_out = map { "$_\n" } @vip_array;
|
the same my $vip_string_out = join "\n", @vip_array;
|
slow write_file( 'file', @vip_array_out );#
|
faster write_file( 'file', \@vip_array_out );#
|
faster then $vip_string_out write_file( 'file', \$vip_string_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{$word}"; }
|
Save hash in insert order use Tie::IxHash;
|
tie %sort_seen, "Tie::IxHash"; use Data::Dumper;
|
$Data::Dumper::Terse = 1; map { $sort_seen{$_} = $seen{$_} } sort keys %seen;
|
print Dumper \%sort_seen; |
|
|
Read config
use YAML::Tiny;
use Carp;
use English;
my $conf =
YAML::Tiny::LoadFile('config.yml')
or croak "Couldn't open YAML::Tiny->errstr: $OS_ERROR";
my $user = $conf->{user};
my $password = $conf->{password};
config.yml is
---
user: 'mishin'
password: 'secret_pw' |
Slices
array slice ($him, $her) = @folks[0,-1];
|
@them = @folks[0 .. 3]; |
hash slice ($who, $home) = @ENV{"USER", "HOME"};
|
list slice ($uid, $dir) = (getpwnam("daemon"))[2,7];
|
@days[3..5] = qw/Wed Thu Fri/; @colors{'red','blue','green'} = (0xff0000, 0x0000ff, 0x00ff00);
|
@folks[0, -1] = @folks[-1, 0];
|
|
Created By
mishin.narod.ru
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets
More Cheat Sheets by mishin