Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read sockets in array using <$socket[i]> in perl

I want to read my sockets and do a "getline" on them.

my @socket1;
$socket1[0] = IO::Socket::INET->new(
    Type     => SOCK_STREAM,
    PeerAddr => "127.0.0.1",
    Proto    => "tcp",
    PeerPort => $dbase_param{camera_stream}
) or die "Cannot open socket on port " . $dbase_param{camera_stream} . ".\n";

print { $socket1[0] } "\n";
my $ligne = <$socket1[0]>;

while ( !( $ligne =~ /Content-Length:/ ) ) {
    $ligne = <$socket1[0]>;
}

It will tell me Use of uninitialized value $ligne in pattern match (m//) for the second $ligne = <$socket1[0]>;

I don't understand wy

like image 944
leykan Avatar asked Jun 25 '26 19:06

leykan


2 Answers

Angle brackets are used also for glob(),

perl -MO=Deparse -e '$ligne = <$socket1[0]>;'
use File::Glob ();
$ligne = glob($socket1[0]);

so if you're not using plain scalar as socket, you might to be more explicit by using readline(),

$ligne = readline($socket1[0]);
like image 50
mpapec Avatar answered Jun 28 '26 13:06

mpapec


The I/O Operator <EXPR> can mean either readline or glob depending on EXPR.

In this instance, you need to use an explicit readline in order to accomplish what you want.

Additionally, you should always perform the reading of a handle in a while loop and put any additional flow logic inside the loop. This is because a while loop that is reading from a file will automatically check for an eof condition. The way that your code is currently written you could end up with an infinite loop if it never finds that regular expression.

To fix both issues, I would therefore rewrite your processing to the following:

my $ligne;

while ( $ligne = readline $socket1[0] ) {
    last if $ligne =~ /Content-Length:/;
}
like image 39
Miller Avatar answered Jun 28 '26 14:06

Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!