Your code is already nearly ready for objects. The "secret" to perl's basic OOP is that the function bless will tell perl that any function call using the syntax $object->method(arg1, arg2...) must be replaced by Package::method($object, arg1, arg2);, where Package can be seen as the type of the object (called class), and is the second argument to bless. Actually if perl can't find the function in the Package/class of the object, it can search in other "parent" classes, but you don't need that here.
When you are creating your first object, you don't have one to call $object->method(), so instead of using the syntax $object->new() you can write my $object = Package->new(), where the string "Package" is the first argument to the call, so that you can use it with bless.
You start with a package declaration:
package Deck; # at the top of the file
Then your sub deck already works well to create one, so to turn it into new, you have to rename it (obviously), fetch the package name in the arguments, and bless the reference (make it an object of type/class "Deck"):
Now you can create your deck with my $deck = Deck->new();my $class = shift; # at the top of the function return bless \@deck, $class; # at the bottom
I told you that $object->method(args...) is turned into method($object, args). So your function deal can already be used in an OO way, simply turn deal($deck, $cards, $hands); into $deck->($cards, $hands);
Now List::Util::shuffle(list) works on a list, not a reference to an array, so a little modification is required since $deck->shuffle() will be turned into shuffle($deck);. Below is one way you could write that. I have written it so that list context (eg: @shuffled = $deck->shuffle()) will return a new list and leave $deck as is, but scalar or void context (eg: ; $deck->shuffle();) will shuffle $deck itself.
Note that since the deck itself is returned in scalar context, you can call other methods on it. So $deck->shuffle()->deal($hands, $cards); would work. Or even Deck->new()->shuffle()->deal(); (Though right now this is a bit useless because shuffle is called again in deal).use List::util; # use the module but do not import shuffle # ... sub shuffle { my $deck = shift; my $out = wantarray ? [] : $deck; @$out = List::Util::shuffle(@$deck); return wantarray ? @$out : $out; }
Edit: for writing code like $object->(ARG1 => value, ARG2 => value); you can start your function with my ($obj, %params) = @_; and use $params{ARG1} and $params{ARG2};
Edit2: s/the secret to \KOOP/perl's basic OOP/
In reply to Re: Let's play poker
by Eily
in thread Let's play poker
by reisinge
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |