Skip to content

Instantly share code, notes, and snippets.

@ernix
Last active November 11, 2019 13:36
Show Gist options
  • Save ernix/47a82f3524f9415170ee8836e7a6e06f to your computer and use it in GitHub Desktop.
Save ernix/47a82f3524f9415170ee8836e7a6e06f to your computer and use it in GitHub Desktop.
perl implementation of python's collection.defaultdict
#!/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