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


in reply to Re: Iterating over verbatim hash reference
in thread Iterating over verbatim hash reference

why would insist on sticking the information in the while loop conditional check instead of a variable?
I have a slight preference for omitting variable names if I don't really need them. But of course, if this would be the only reason, I would say in this case: What the heck, let's name the variable and forget it. But the truth is, once I stumble over such a problem, I get interested in the problem as such, because it indicates that this might lead to some aspect of Perl programming which I have not understood yet - and that's the main reason why I'm looking for a solution.

-- 
Ronald Fischer <ynnor@mm.st>

Replies are listed 'Best First'.
Re^3: Iterating over verbatim hash reference
by Herkum (Parson) on Jan 21, 2010 at 19:27 UTC
    Variables can help you clarify what you code does. Something an obscure data structure does not. For example,
    my $DEBUG = 1; #... later in your code if ($DEBUG) { warn "Something happened\n" }

    I bet your thinking that this is pretty obvious but I still want to reduce the number of variables.

    If you think you have too many variables in a section of code, chances are you have not abstracted out it out enough. Move more of your code into other subroutines to enhance clarity.

    my $dimensions = _get_dimensions_for(5,8); while (my ($r,$s) = each %{ $dimensions } ) { print($r); } sub _get_dimensions_for { my $x = shift; my $y = shift; return { x=> $x, y=> $y } }

    Note: Thanks to ikegami for pointing out my error.

      Doesn't your snippet still suffer from the problem?
Re^3: Iterating over verbatim hash reference
by AnomalousMonk (Archbishop) on Jan 21, 2010 at 19:11 UTC
    I have a slight preference for omitting variable names if I don't really need them.

    If you are concerned about cluttering up a (possibly over-broad) scope with needless nonce variable names (not an entirely unreasonable concern, IMO), why not just enclose the sub-section of code in its own limited sub-scope?

    >perl -wMstrict -le "{ my %h = qw(a 1 b 2 c 3); while (my ($k, $v) = each %h) { print qq{$k -> $v}; } } " c -> 3 a -> 1 b -> 2
      why not just enclose the sub-section of code in its own limited scope?

      Simply for reason of aesthetics ;-)

      As was already pointed out, there are many ways to skin the cat. I was just wondering whether Perl language really dictates us here to introduce a variable name, since in all other cases I can think of, an expression which is only needed once, doesn't need to be named. Having found this case where I could not do without introducing a variable, I considered it more likey that I was just missing some feature of Perl...
      -- 
      Ronald Fischer <ynnor@mm.st>