Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: To initialise or not to initialise?

by Abigail-II (Bishop)
on Jun 24, 2004 at 08:42 UTC ( #369266=note: print w/ replies, xml ) Need Help??


in reply to To initialise or not to initialise?

If context or variable name doesn't make clear what a variable means, or is used for, one should add a comment. What would be your default value for a variable that's going to hold a reference to an object? Or a variable that could hold both a string and a numerical value? And if you assign 0, does that mean the variable will only hold integers? Only non-negative integers? Any numerical value? But even if you know, what insight to the program did it give to you?

I initialize variables only if it makes sense. I also tend to declare variables at their first use, which usually means the first time something is assigned to it - or it's done a line above the first assignment. Note that assigning default values will take time, although for larger blocks it won't matter too much:

#!/usr/bin/perl use strict; use warnings; use Benchmark qw /cmpthese/; cmpthese -5 => { init => 'my $title = ""; my $page = 0; my $chapter = 0; $title && $page && $chapter', def => 'my ($title, $page, $chapter); $title && $page && $chapter', }; __END__ Rate init def init 1165121/s -- -38% def 1876595/s 61% --

Abigail


Comment on Re: To initialise or not to initialise?
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://369266]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2014-11-28 01:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (191 votes), past polls