in reply to Re: Not quite an OO tutorial
in thread Not quite an OO tutorial
First off remember that the sample code in the OP was intended as demo code that touches a little on a real problem, but isn't intended as a serious solution to the original problem. In particular it doesn't scale well - that is, it really is a bad solution if you want to add many, many different groups of random things.
A better solution if you want to add many different types of random things is to write a class that addresses that issue. There are many ways you could do that. Given that the list is likely to grow over time and that groups of things may be added at run time having a few different ways of adding groups is probably needed. I'd start with something like this:
use strict; use warnings; package RandThing; use overload '""' => 'getValue'; my %_groups; # Load default groups while (<DATA>) { chomp; next if ! length; my ($type, @values) = split /,/; $_groups{$type} = \@values; } return 1; sub new { my ($class, $type, @values) = @_; die "RandThing::new must be called using RandThing->new ('type') s +yntax!\n" if ! defined $class || ref $class; die "$class->new requires a group type parameter\n" if ! defined $type; die "Group type $type is unknown and no values given to define a n +ew type\n" if ! exists $_groups{$type} && ! @values; if (! @values) { # Use an existing group @values = @{$_groups{$type}}; } elsif (ref $values[0]) { $_groups{$type} = \(@values = doLAMagic (@values)); } else { # Add a new group or update an old one $_groups{$type} = \@values; } my $self = bless {values => \@values}, $class; $self->genValue (); return $self; } sub doLAMagic { my ($list, $key) = @_; my @values; return @$list if 'ARRAY' eq ref $list; return @{$list->{$key}} if exists $list->{$key}; return keys %{$list} if $key eq 'keys'; return map (@{$list->{$_}}, keys %{$list}) if $key eq 'all'; $key = 'undef value' if ! defined $key; die "Can't do LA magic on a hash using $key. 'keys' or 'all' requi +red"; } sub getValue { my ($self) = @_; return $self->{value}; } sub genValue { my ($self) = @_; $self->{value} = $self->{values}[rand @{$self->{values}}]; return $self->{value}; } __DATA__ Weather,stormy,windy,rainy,calm Light,bright,dark,gloomy,dazzling DayPart,morning,evening,afternoon,night
which can be used in similar fashion to the previous sample:
use strict; use warnings; use RandThing; my $dp = RandThing->new ('DayPart'); my $lt = RandThing->new ('Light'); my $wt = RandThing->new ('Weather'); my $tense = RandThing->new ('Tense', 'was', 'is', 'will be'); my $la = RandThing->new ('LA', [qw(Lady Aleena magic)]); print "It $tense a $lt and $wt $dp ($la).\n";
Now you still have the overload magic, a bunch of default group types, the ability to add new group types and a simple way of extending the list of default group types. Oh, and for good measure I tossed in some Lady Aleena magic ;).
|
---|