Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: where to declare a variable...

by dvergin (Monsignor)
on Dec 09, 2001 at 08:28 UTC ( [id://130507]=note: print w/replies, xml ) Need Help??


in reply to where to declare a variable...

Before the "if" blocks.

A common rule of thumb is that you want to declare the variable in as narrow a scope as you can and still be able to access it where you need to.

So you could try declaring the array inside the if blocks for a very narrow scope. But then you would discover that you were not able to access it outside the scope of the if blocks -- which I presume you will want to do when you flesh out the subroutine (otherwise why load the contents of the file into the array in the first place).

------------------------------------------------------------
"Perl is a mess and that's good because the
problem space is also a mess.
" - Larry Wall

Replies are listed 'Best First'.
Re(2): where to declare a variable...
by dmmiller2k (Chaplain) on Dec 09, 2001 at 23:12 UTC
    ... you want to declare the variable in as narrow a scope as you can and still be able to access it where you need to.

    ++dvergin!

    Of course, this assumes that the fragment presented was whittled down to some minimum amount needed to ask the question.

    In other words, it's probably safe to presume that the if block would be followed by code which does something with the @entries array, such as return a reference to it or its contents, in which case perhaps something like this is more appropriate:

    sub openFile { my ($file1, $file2) = @_; # assume these are passed as parameters my $fn = $file1 || $file2; # replaces the 'if' in original open FH, $fn or die "$fn: $!"; my @entries = <FH>; close FH; # in list context, return the entire array, else (scalar context) a +ref return wantarray ? @entries : \@entries; }

    dmm

    
    You can give a man a fish and feed him for a day ...
    Or, you can teach him to fish and feed him for a lifetime
    
Thanks :)
by kiat (Vicar) on Dec 10, 2001 at 20:37 UTC
    Hi All, A big thank you for taking the time to respond to my question on 'my'. This is definitely a place I'll keep coming back.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-03-29 11:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found