Last active
November 11, 2019 13:36
-
-
Save ernix/47a82f3524f9415170ee8836e7a6e06f to your computer and use it in GitHub Desktop.
perl implementation of python's collection.defaultdict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
{ | |
package Tie::DefaultDict; | |
require Tie::Hash; | |
our @ISA = qw(Tie::ExtraHash); | |
sub TIEHASH { | |
my ($class, $default, %h) = @_; | |
my $self = bless [+{%h}, $default], $class; | |
return $self; | |
} | |
sub STORE { | |
my ($self, $key, $value) = @_; | |
$self->[0]->{$key} = $value; | |
} | |
sub FETCH { | |
my ($self, $key) = @_; | |
if (!exists $self->[0]->{$key}) { | |
$self->[0]->{$key} = $self->[1]->(); | |
} | |
return $self->[0]->{$key}; | |
} | |
} | |
tie my %link_to, 'Tie::DefaultDict', sub { "fallback" } => ( | |
google => "www.google.com", | |
apple => "www.apple.com", | |
); | |
print $link_to{apple}; | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment