Created
September 6, 2012 07:09
-
-
Save ynonp/3652397 to your computer and use it in GitHub Desktop.
Zombie games
This file contains hidden or 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
package Anagram; | |
use Moose; | |
use v5.14; | |
# has means data member | |
has 'word', required => 1, is => 'ro', isa => 'Str'; | |
has 'normalized_word', lazy_build => 1, is => 'ro'; | |
# my means static | |
my @dictionary_words; | |
sub _build_normalized_word { | |
my $self = shift; | |
return _normalize( $self->word ); | |
} | |
sub _normalize { | |
my ( $word ) = @_; | |
return lc join('', sort split //, $word); | |
} | |
sub is_anagram { | |
my ( $self, $other_word ) = @_; | |
_normalize( $other_word ) eq $self->normalized_word; | |
} | |
sub print_all_anagrams { | |
my $self = shift; | |
my @words = read_dictionary_file(); | |
foreach my $w ( @words ) { | |
say $w if $self->is_anagram( $w ); | |
} | |
} | |
sub read_dictionary_file { | |
return @dictionary_words if @dictionary_words; | |
open my $fh, '<', '/usr/share/dict/words'; | |
@dictionary_words = <$fh>; | |
chomp @dictionary_words; | |
close $fh; | |
return @dictionary_words; | |
} | |
1; |
This file contains hidden or 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
use v5.14; | |
use warnings; | |
use Zombie; | |
use Data::Dumper; | |
my $z1 = Zombie->new; | |
my $z2 = Zombie->new; | |
$z1->eat_brain(); | |
$z1->eat_brain(); | |
$z2->eat_brain() for (1..7); | |
say "Z1 ate ", $z1->size(), " brainz"; | |
say "Z2 ate ", $z2->size(), " brainz"; | |
$$z1 = 950; | |
say "Z1 ate ", $z1->size(), " brainz"; | |
This file contains hidden or 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
package Zombie; | |
###################### | |
# Zombie.pm | |
# | |
# A class for eating all your brainz | |
# | |
my @counters; | |
my $index = 0; | |
sub new { | |
my ( $cls ) = @_; | |
my $x = $index++; | |
my $self = \$x; | |
bless $self, $cls; | |
return $self; | |
} | |
sub size { | |
my $self = shift; | |
my $index = $$self; | |
return $counters[$index]; | |
} | |
sub eat_brain { | |
my $self = shift; | |
$counters[$$self] += 1; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment