January 2023 Archives

How to prevent an infinite loop

This loop (assuming you have an /etc/passwd and may read it) runs forever:

while () {
  open my $fh, '<:unix', '/etc/passwd' or die $!;
}

This loop terminates:

while () {
  open my $fh, '<', '/etc/passwd' or die $!;
  binmode $fh, ':unix';
}

Note that you will have to live with some extraneous output:
Too many open files at t.pl line 2.

Btw, you can make it loop forever again this way:

require POSIX;
while () {
  open my $fh, '<', '/etc/passwd' or die $!;
  binmode $fh, ':unix';
  POSIX::close fileno $fh;
}

About Aristotle

user-pic Waxing philosophical