From:                   Richard Smith <[EMAIL PROTECTED]>

> I have had problems using "my" when refering to File Handles,
> especially when I wish to pass them to subroutines.  I have also had
> problems declaring them with $ or @, and have been forced to use:
> local *logHandle; Is this because I am declaring the actual
> filehandle, and not a reference to it? 
> Thanx, Smiddy

IMHO the FILEHANDLES were an unlucky idea.

Yes if you use the normal filehandles with no leading character you 
can use only local. You should be aware of a gotcha though ...

When you say

        local *FILEHANDLE;

you are not only localizing the FILEHANDLE, but also variables 
$FILEHANDLE, @FILEHANDLE and %FILEHANDLE and 
subroutine &FILEHANDLE !

So if you happen to have a variable with the same name as a 
filehandle you'll mask it when localizing the filehandle.

Also if you need to pass the filehandle anywhere it's a bit messy.
You have to play with globs etc.etc.etc.

So it's much better to use the FileHandle or IO::Handle or 
IO::Socket or ... objects instead. Since they are "normal" scalars 
and can be treated normaly. They can be my()ed, they can be 
passed around, they can be stored in data structures, etc. :


        use FileHandle;
        ...
        sub foo {
                my $file = shift;
                my $FH = new FileHandle "< $file"
                        or die "Can't open $file : $!\n";
                
                my $fline = <$FH>;
                return ($fline, $FH);
        }

        my ( $firstline, $HANDLE) = foo 'c:\boot.ini';
        ...

with recent Perls you don't even have to use the new FileHandle.
In 5.6 even this will work:

        use FileHandle; # NECESSARY!

        open my $FH, "< $file" or ...

You can do similar things with socket()s both "low level way" and 
via IO::Socket (prefered) :

        my $s = FileHandle->new();
        socket($s, AF_INET, SOCK_STREAM, 25);
        connect($s, 
                pack('Sna4x8', AF_INET, 25, pack('C4',127,0,0,1)));
        print $s "EHLO my.silly.machine\r\n";
        ...

When doing this you have to remember one thing.

The thing within <>s and after "print" must be either a 
FILEHANDLE or a $variable or (only in case of print statement) a 
{block}.

This
        $line = <$sockets[$i]>;
and
        print $sockets[$i] "Hello World\r\n";
will not work.

This

        my $s = $sockets[$i];
        $line = <$s>;
        print $s "Hello World\r\n";

and

        print {$sockets[$i]} "Hello World\r\n";

will.

Try also
        perldoc -q filehandle

HTH, Jenda


=========== [EMAIL PROTECTED] == http://Jenda.Krynicky.cz ==========
There is a reason for living. There must be. I've seen it somewhere.
It's just that in the mess on my table ... and in my brain.
I can't find it.
                                        --- me

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to