in reply to Sub Routine Problem
I personally believe that "simplicity is the ultimate sofistication" (Cit.) - indeed I had serious difficulties wandering through your code to understand what it does. Said this, and having seen code from others in this thread too, I think that your sub may be made just as simple as:
{ my @card_map = qw(zero one two three four five six seven eight nin +e); sub card { my ($n, $pre) = map { $_< 0 ? (-$_, 'minus ') : ($_, '') } shi +ft; $pre . ($card_map[$n] // $n); } }
Here, I preferred to move @card_map out of the sub because I see no point assigning to it each time the sub is called. (I also changed "negative" to "minus" which I think is proper English.)
Update: Limbic~Region /msg'd me to point out that probably "it will be a while before state declared variables become common place due to compatability issues but that would be his preference here." Indeed, he's right, and I'm using 5.10.0's // (although in this case || would suffice) under use 5.010 anyway, so I thought that for completeness I may rewrite the sub in that form as well:
sub card { state @card_map = qw(zero one two three four five six seven eight +nine); my ($n, $pre) = map { $_< 0 ? (-$_, 'minus ') : ($_, '') } shift; $pre . ($card_map[$n] // $n); }
Fortunately, I tested the code before pasting it here, which wouldn't have been obvious since "there's no reason why I shouldn't work" but unfortunately there's one:
C:\temp>perl kg.pl Initialization of state variables in list context currently forbidden +at kg.pl l ine 10, near "qw(zero one two three four five six seven eight nine);" Execution of kg.pl aborted due to compilation errors.
This actually led me to discover something that I and appearently Limbic~Region didn't even remotely suspect, but is well documented in perldoc perlsub:
When combined with variable declaration, simple scalar assignment to state variables (as in state $x = 42 ) is executed only the first time. When such statements are evaluated subsequent times, the assignment is ignored. The behavior of this sort of assignment to non-scalar variables is undefined.
Well, to be very fussy, the documentation is not entirely consistent with the implementation since the former says that the behaviour of the assignment is "undefined" whereas the latter strictly prohibits it - and I checked, to be sure, that it is not a strict thing: even if you don't use it, compilation fails.
|
|---|