Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re^2: Perl Style: Is initializing variables considered taboo?

by ait (Friar)
on Aug 21, 2010 at 17:20 UTC ( #856491=note: print w/replies, xml ) Need Help??

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

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.

Replies are listed 'Best First'.
Re^3: Perl Style: Is initializing variables considered taboo?
by LanX (Bishop) on Aug 21, 2010 at 17:43 UTC
    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:

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

    Cheers Rolf

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://856491]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2018-01-23 22:37 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (254 votes). Check out past polls.