in reply to Style: buried variables or double referencing?

This would be my solution.
use constant LONG_COUNT => 14; use constant SHORT_COUNT => 9; my $some_variable; # ... my $loop_count = $some_variable eq 'x' ? LONG_COUNT : SHORT_COUNT; for $i (0 .. $loop_count) { # do some stuff print $i; }
You might even get rid of loop_count and use (0 .. $some_variable eq 'x' ? LONG_COUNT : SHORT_COUNT) directly.

Now LONG_COUNT and SHORT_COUNT will be easy to find and you can document them at the use constant.

-- gam3
A picture is worth a thousand words, but takes 200K.

Replies are listed 'Best First'.
Re^2: Style: buried variables or double referencing?
by tilly (Archbishop) on Aug 20, 2005 at 18:12 UTC
    TheDamian's Best Practices gives several good reasons why constant should be deprecated in favour of Readonly. In which case you would have:
    use Readonly; Readonly my $LONG_COUNT => 14; Readonly my $SHORT_COUNT => 9; # ...
    I fully agree with his recommend since I never saw that constant buys me anything useful.

      Depends. Readonly is slow, and not everyone can use Readonly::XS. The following code takes 48 seconds:

      use Readonly; Readonly $C1 => 1; my $t0 = time(); my $a = 2; for (1 .. 10000000) { if ($a ++ == $C1) { ; } } print time() - $t0;

      When this takes 4 second:

      use constant C1 => 1; my $t0 = time(); my $a = 2; for (1 .. 10000000) { if ($a ++ == C1) { ; } } print time() - $t0;

      If performance is important, use constant.

        I'd be happier developing with a function that called Readonly in development and then something like this in production:
        sub fake_readonly { $_[0] = $_[1]; }
        And now you get most of the advantages of Readonly, but performance is not a problem. (I don't like constant because I'm a big fan of interpolating, and I often have to check whether someone has a constant or function because I'm afraid that it will try to suck up arguments.)
        That's a difference of 4.4 microseconds. That's a difference I'm willing to take in most of my programs.

      TheDamian's <cite>Best Practices</cite> gives several good reasons why constant should be deprecated in favour of Readonly:

      Readonly my $LONG_COUNT => 14; Readonly my $SHORT_COUNT => 9;

      But Damian also says in his book that you should use hashes for look-up tables, rather than if/else tests. And that's definitely a look-up table.

      So how about something like:

      Readonly \my %THWAPP_COUNT => ( x => 14, y => 9, );

      (Adjective describing what sort of a count this is courtesy of Acme::MetaSyntactic::batman.)

      Smylers