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

If you're using my, initialising with undef is just make-work, as lexical variables are automatically initialised to undef.

If you're not using my, then this is another reason to start.

  • 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 LanX (Saint) on Aug 21, 2010 at 15:29 UTC
    I don't understand ... Why you are restricting this behavior to my...?

    Every non-initialized variable is not defined.

    DB<1> print $a // "undef" undef DB<2> my $a;print $a // "undef" undef DB<3> our $a;print $a // "undef" undef DB<4> $a=1;print $a // "undef" 1
    UPDATE:

    And in most cases accessing an undefined variable will be caught under use warning;.

    DB<1> print $a DB<2> use warnings; print $a Use of uninitialized value $a in print at (eval 6)[/usr/share/perl/5.1 +0/perl5db.pl:638] line 2. .. DB<3> use warnings; $a=undef;print $a Use of uninitialized value $a in print at (eval 9)[/usr/share/perl/5.1 +0/perl5db.pl:638] line 2. .. DB<4> print $a++ 0

    Notable exceptions of this warnings are some altering operators like ".=" and "++" and auto-vivication in hashes and arrays.¹

    Cheers Rolf

    1) anything else?

    ... of course boolean context including the defined operator won't throw a warning.

      Why you are restricting this behavior to my...? Every non-initialized variable is not defined.

      Unless is was used in module you called, or the previous iteration of the loop, or call to sub, or ...

      They may start out as undef, but only for the first use.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        > Unless is was used in module you called, or the previous iteration of the loop, or call to sub, or ...

        ...which describes "already initialized".

        UPDATE:

        IMHO your intention is to control the scope of a variable.

        my is only one mean to achieve this, our, state, local are others.

        Cheers Rolf

Re^2: Perl Style: Is initializing variables considered taboo?
by ait (Hermit) on Aug 21, 2010 at 15:41 UTC
    Of course I use strictures in all my code! Why else would I be asking about variable initialization if I did not predeclare them?
    The question was more on style (hence "Perl Style") and the fact that the pod for my in perlfunc does not specify if it actually initializes the variable to any specific value.
    Nevertheless, after your response I discovered that perlsyn pod does under "Declarations" and quite extensively explains the initialization details. It seems that in a few cases it is wise to initialize, but not to undef, because as you say, it is just plain wasteful. Though IMHO I still think it just looks neater in the code, but shall refrain from doing so to undef in the future.
    I have a faint memory that I picked up the practice many years ago from the Camel book (or PBP), and I think it states somewhere that it is good practice to always initialize variables, but I could be wrong... or maybe it's just an old habit from my background in C.
      there are cases where assigning undef makes sense but generally it's a waste of time (which is not Perl style ;)

      Applications are especially when passing "positional" lists or assigning to lists, with "gaps".

      i.e.

      ($a,undef,$b)=@array; # ignore second parameter
      or
      function($a,undef,$b) {..} # treat second parameter as not suppl +ied

      The latter is especially necessary if you are checking arguments within the sub for definedness and changing to default values.

      UPDATE: An extension of this case is a hash or array element which exists but is not defined!

      > Of course I use strictures in all my code!

      it's more about use warnings to be warned about undefined variables.

      UPDATE:

      and please be careful not to return undef to "explicitly" return false.

      Subs return lists, so what you are actually doing is returning a one-element list instead of an empty one. I.e. @array=func();

      Using a blank return is the same like return (); and won't byte you in list context but in scalar context the variable will be undef anyway.

      Cheers Rolf

        If I need to discard a value from an array or from a list of return values, I usually index the list, rather than assign values into undef.
        ($a, $b)= @array[1,3]; my ($minutes, $hours) = (localtime())[2,3]
        Though the localtime example is artificial, I rarely do anything with list-context localtime(), anymore, other than feed it into Posix::strftime().

        --
        TTTATCGGTCGTTATATAGATGTTTGCA

        and please be careful not to return undef to "explicitly" return false.
        Many people use return undef to indicate false in the execution of a sub, but it's likely I'm really not getting what you mean by "explicitly":
        perl -e 'foreach (@INC){print "$_\n" unless $_ eq q{.}}' | xargs grep +-R "return undef" | wc -l<br> 1752
        Subs return lists, so what you are actually doing is returning a one-element list instead of an empty one. I.e. @array=func(); Using a blank return is the same like return (); and won't byte you in list context but in scalar context the variable will be undef anyway.
        I have found it wise to always return an explicit value, to avoid a potential bite or 'feature' of the "last expression", and have till now, used undef to indicate falseness and failure, and a defined value or "1", to indicate trueness/success.

        As you point out, it is often overlooked that Perl returns lists and as a result most of the time subs are evaluated in scalar context; in OO code it's customary to return a single ref to an object or undef on failure. So what exactly do you mean by not returning undef to "explicitly" return false.
      Of course I use strictures in all my code!

      I did say "if". Not everybody uses strict; and I don't know you from the next guy; so there is no "of course" about it.

      Why else would I be asking about variable initialization if I did not predeclare them?
      Because initialising/reinitialising your variable to undef becomes very important if you don't use my, because globals have this habit of retaining their values from previous iterations of loops, and previous calls to subroutines.

      As for style, that is in the eye of the beholder. I find much perlstyle a total anathema; often supported by nothing more than justifictions.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
      I've read through the posts and there is certainly a lot of verbage here!

      As long as you aren't using the very ancient C style where all the variables had to be declared at the beginning of the sub instead of when they are first used or close to where they are first used as in modern C, I don't see any problem at all.

      Often I see my @x=(); vs just my @x;, but I don't see any big point to get really riled up about! I seldom see a statement with a scalar like my $x=undef; vs my $x; because something happens with $x in the next line or two. An array or hash declaration happens more often closer to the beginning of the code and can have a wider distance between declaration and use.

      Of the universe of style issues, this issue probably shouldn't be at the "top of your hit parade".