develooper Front page | perl.beginners | Postings from February 2002

RE: Sockets in an array

Thread Previous | Thread Next
Jenda Krynicky
February 25, 2002 12:02
RE: Sockets in an array
Message ID:
From:           	Richard Smith <>

> 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


you are not only localizing the FILEHANDLE, but also variables 
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);
		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 

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


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


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


Try also
	perldoc -q filehandle

HTH, Jenda

=========== == ==========
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

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About