in reply to Re: Mathematics skills
in thread Mathematics skills

If I do not explicitly want a specific initial value for a variable, I purposely leave it undefined so that I get a warning if I use it before I was planning to.

If I do not want an explicit initial value for a variable, I tend to set it explicitly to undef. It tends to pair up well with a latter test for definedness, and it also shows that I have considered that the variable containing an undefined value is actually, er, defined behaviour. Consider the snippet:

my $key = undef; for my $k( keys %h ) { $key = $k if $h{$k} eq 'foo'; } if( defined $key ) { # ... }

I find it makes it clearer to see that the variable starts out undefined and that the loop could set the variable to some value.


print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'

Replies are listed 'Best First'.
Re^3: Mathematics skills
by Aristotle (Chancellor) on Oct 12, 2002 at 17:59 UTC
    I'm not sure that makes sense. Someone fluent in Perl is supposed to know that my $var; leaves $var undefined. I wouldn't consider the following any less readable than your code - or maybe, vice versa, don't consider your code any more readable than the following:
    my $key; for my $k( keys %h ) { $key = $k if $h{$k} eq 'foo'; } if( defined $key ) { # ... }
    It's the same as using $_ - you can of course go and write
    while(defined($_ = <STDIN>)) { next unless $_ =~ /^something/; # ... }
    but in my opinion, that is, if anything, less rather than more readable. It's more accomodating to a Perl beginner maybe, who would be a bit lost as to what's happening if the idiomatic forms were used, but it's a whole lot more laborous to read too. But that may just be my personal preference.

    Makeshifts last the longest.