in reply to Perl Style: Is initializing variables considered taboo?

The standard references for style are perlstyle and Perl Best Practices, and neither say anything about initialising variables specifically. PBP says to initialise localised variables, but you specifically mention my. PBP also says to initialise attributes, but again that's probably not what you mean.

perltidy does not appear to care, and Perl::Critic is silent on the matter.

My view is that if you have a good reason to initialise them then do so, if not, why bother? You don't have to impress anyone else, do you?
  • Comment on Re: Perl Style: Is initializing variables considered taboo?

Replies are listed 'Best First'.
Re^2: Perl Style: Is initializing variables considered taboo?
by ait (Hermit) on Aug 21, 2010 at 17:20 UTC
    As to impress no, though I usually try to make code look good as well as it works.
    Initializing variables to something has seemed neater and more legible, though I had never given it much thought till today. For example this IMO looks neater:
    my $foo = 0; my $bar = undef;
    Than this:
    my $foo = 0; my $bar;
    I think ikegami understood perfectly where I was comming from with this thread.
      IMHO there is no possibility in Perl to distinct between:

      my $a and my $a=undef

      "Assigning the value undef" (dangerous discription) of a scalar is always completely transparent to "has no value at all".

      If I'm wrong, I'd appreciate if someone can show me code proving me false.

      Furthermore you can't safely use "value comparisons" with undef.

      DB<33> my $a; print $a==undef 1 DB<34> my $a; print $a==0 1 DB<35> my $a=undef; print $a==0 1 DB<36> my $a=undef; print $a eq undef 1 DB<37> my $a=undef; print $a eq 0 DB<38> my $a=undef; print $a eq "" 1

      you need to use the special builtin defined.

      Thats why I think it's the better stile to avoid undef if not necessary.

      When you need to reset already declared and potentially initialized variables (in the sense of "setting to an non intialized state"):

    • for multiple vars you can assign an empty list:
      ($a,$b)=();

    • to reset a single scalar you can alternatively chose to write:
      undef $a;
      (but actually I never do this myself)

      Cheers Rolf