http://qs321.pair.com?node_id=32316


in reply to cursebox v0.9 - "The Cursed Jukebox"

Update: Please use strict; !

Though I have not used this code, I have one comment to make in the spirit of TIMTOWTDI (hopefully a good comment) - I find the simulated switch statement to map a keypress to an action rather clumsy, as it does not really allow to easily add other actions later or add other actions dynamically.

In such situations, I prefer to use a hash of code references, like this :

my %actions = ( "n" => \&skip, "m" => \&movesong, # ... rest ommited ... "\n" => \&goto, );
and the routine interpretplay() would then look like this (sadly, untested) :
sub interpretplay { if (exists $actions{$char}) { &$actions{$char}; } else { &invalid; }; };
or, if the whole state machine would be changed to use hashes, one could even use a single interpret() method that would simply look at the $current_state hash reference to find the action to be executed.

Dynamically loaded actions would then simply modify the %actions hash with their entry.

Replies are listed 'Best First'.
(jcwren) RE: cursebox v0.9 - switch{} coding style
by jcwren (Prior) on Sep 15, 2000 at 05:57 UTC
    This is sample code for odie to look at, and will probably be changing. Please don't vote on this node.
    #!/usr/local/bin/perl -w use strict; { my %hash = ('a' => {-func => \&sub_one, -parm => 'subone'}, 'b' => {-func => \&sub_two, -parm => 'two,two_a,two_ +b'}, 'c' => {-func => \&sub_three, -parm => ''}, ); &{$hash {'a'}->{-func}} (split ',', $hash {'a'}->{-parm}); &{$hash {'b'}->{-func}} (split ',', $hash {'b'}->{-parm}); &{$hash {'c'}->{-func}} (split ',', $hash {'c'}->{-parm}); } sub sub_one { print "sub_one got ", scalar @_, " parameters\n"; print "sub_one parameters: $_\n" foreach (@_); } sub sub_two { print "sub_two got ", scalar @_, " parameters\n"; print "sub_two parameters: $_\n" foreach (@_); } sub sub_three { print "sub_three got ", scalar @_, " parameters\n"; print "sub_three parameters: $_\n" foreach (@_); }
    --Chris

    e-mail jcwren
RE: RE: cursebox v0.9 - switch{} coding style
by odie (Sexton) on Sep 13, 2000 at 23:06 UTC
    Well... As I said, it is version 0.9 and the code is a complete mess. The whole thing started as a sinple recursive hack that played every mp3 file found, using mpg123. I honestly didn't expect to continue building it... =)
    I will naturally make the code a lot more efficient, and less spammy, and use strict. This code is still very much in a state of "hack". Version 1.0 will be posted when complete.