lundi 24 février 2014

Re: use strict; use warnings; topic




Am 24.02.2014 06:31, schrieb Marek Novotny:
> ...
> @startingdeck = ("A H","2 H","3 H","4 H","5 H","6 H","7 H","8 H",
> "9 H","10 H","J H","Q H","K H",
> "A D","2 D","3 D","4 D","5 D","6 D","7 D","8 D",
> "9 D","10 D","J D","Q D","K D",
> "A C","2 C","3 C","4 C","5 C","6 C","7 C","8 C",
> "9 C","10 C","J C","Q C","K C",
> "A S","2 S","3 S","4 S","5 S","6 S","7 S","8 S",
> "9 S","10 S","J S","Q S","K S");
> ...


Beside your problem you asked,
one important lesson in programming is to avoid to reapeat yourself,
as we are lazy :-) and more important it would be heart to maintain
(change or update your program in future).
Just imagine here, you might also play with a double deck or with jokers
or without deuces (or you'd prefer to have an other starting deck order
of cards), than with this way, you would have to copy+paste and replace
it manually with a lot of keystrokes. Not only is this boring, more
important, it is easy to make a mistake doing so.

Here a nice and simple way that also fits into your course (working with
arrays and loops would be) [untested]:

my @startingdeck = ();
foreach my $rang (2 .. 9, qw/T J Q K A/) {
foreach my $color(qw/H D C S/) {
push @startingdeck, "$rang $color";
}
}
# Starting deck is now filled with a classic 52 card deck

So it's easy to read, short to write and easy to change,
and most important you Don't Repeat Yourself (DRY-principle).


Greetings,
Janek

PS: You problably don't know yet what this qw/../ operator means,
here it's just a short cut for
qw/H D C S/ is the same as ("H", "D", "C", "S").





Aucun commentaire:

Enregistrer un commentaire