in reply to Confusion in naming variables in subroutines

For unrelated reasons*, I don't like working at the global level. This has the side-effect of avoiding the issue.

#!/usr/bin/perl -w { my ( $length, $breadth, $height ) = ( 10, 20, 30 ); my $volume = calc_volume( $length, $breadth, $height ); print "\nvolume = $volume\n"; } sub calc_volume { my ( $length, $breadth, $height ) = @_; my $volume = $length * $breadth * $height; return $volume; }

While the snippet you provided has two variables with the same name in scope at the same time, the snippet I provided does not.

* — First, it makes the scope of variables much larger than it needs to be. Secondly, global objects are destroyed in an unpredictable order. That means a child object can be reaped before its owners is, which is bad if you have a custom destructor.

Replies are listed 'Best First'.
Re^2: Confusion in naming variables in subroutines
by jbert (Priest) on Jan 24, 2007 at 10:49 UTC
    Ditto. I generally start all but the most trivial (and often even those) scripts something like:
    #!/usr/bin/perl use strict; use warnings; exit !main(@ARGV); sub main { my $fname = shift; # etc... foo() or return; # Will lead to a non-zero (i.e. unsuccessful) exit-code return 1; # All went well (will lead to a successful exit code of 0) } sub foo { }
    And the reason for this is at least in part to avoid having unintentional whole-file-scope for the lexical variables in the 'main' code. Having the 'exit' in there too means one doesn't have to eyeball the entire file looking for executable code at file scope. (It does mean that if you want any file-scope lexicals, you need to put them before the call to 'main', but to me that's actually a feature.)