On Friday, August 2, 2002, at 08:09 , Chad Kellerman wrote:
[..]
> ** I always have issues with scope.... Can I use Sys::Hostname just in
> the subroutine, or any perl module for that matter? Or do I have to use
> it globally?
>
> $host=hostname; finds that daggone hostname and I have hostname all over
> te place....my bad. :^(.
[..]
there are two strategies I hear you are asking about:
a) the difference between 'use v. require'
b) the scoping of variables
plan A:
#!/usr/bin/perl -w
use strict;
use Sys::Hostname
......
sub Freak_Out {
my $msg = shift;
.....
my $host = hostname;
....
}
the 'use' of course is essentially 'require foo && import foo'
so we imported the function there - and might not remember where
we got that function from - especially if we did not annotate
it up at the top of the script.
so you might try
plan B:
#!/usr/bin/perl -w
use strict;
.....
sub Freak_Out {
my $msg = shift;
.....
require Sys::Hostname;
my $host = Sys::Hostname::hostname();
....
}
and completely ISOLATE the fact that you are using
the hostname() function there.
Your Third strategy would be something on the order of say
#!/usr/bin/perl -w
use strict;
use Sys::Hostname
my $host = hostname;
......
sub Freak_Out {
my ( $from_host, $msg ) = @_;
....
}
hence requiring the caller to define it.
What I personally would consider the worst of all possibles
in this is the 'leaking global gag':
#!/usr/bin/perl -w
use strict;
use Sys::Hostname
my $host = hostname;
......
sub Freak_Out {
my ( $msg ) = @_;
....
Log($host, $msg);
...
}
where you USE the globally defined '$host' without passing
it into the function.... this type of 'side effect' gets
ugly the first time you try to re-use the function Freak_Out()
somewhere else.... and forget that you were using a global
variable by indirection.
HTH
ciao
drieux
---
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]