I'm working on a script for the VoIP software, Freeswitch. The script will run as an instance listening for inbound messages to a socket.
I used an example script provided with Freeswitch, to start with, and everything works fine.
However, one bit is throwing me off.
use IO::Socket::INET;
use warnings;
use strict;
my $sock = new IO::Socket::INET ( LocalHost => '127.0.0.1', LocalPort => '8060', Proto => 'tcp', Listen => 1, Reuse => 1 );
die "Could not create socket: $!\n" unless $sock;
for(;;) {
my $new_sock = $sock->accept();
my $pid = fork();
if ($pid) {
close($new_sock);
next;
}
close($new_sock);
}
What exactly does the ;;
mean? Is it a special operator that is defined when a socket is created? Struggling to find documentation!
for(;;)
is a C-ish idiom which is read as for ever
, and is a loop that never terminates. People who don't come from C would write while (1)
instead.
Normally, this C-style for
loop has three statements: initialization, looping condition, and some step:
for (init; condition; step) {
body;
}
which is exactly equivalent to
{
init;
while (condition) {
body;
}
continue {
step;
}
}
An empty condition
is taken to be always true.
A common usage would be to iterate over all numbers in a range:
for (my $i = 0; $i < @array; $i++) {
say $array[$i];
}
However, this would be written more idiomatically with a foreach loop:
for my $i (0 .. $#array) {
say $array[$i];
}
or
for my $item (@array) {
say $item;
}
which is why you see the C-style for loop very rarely in idiomatic Perl code.
This construct is documented in perldoc perlsyn
.