Perl::...orLoop(3pm)

🌸 NAME 🌸

okay so this is the Perl::...orLoop(3pm) page β€” yes, that's the manual name β€” straight out of User Contributed Perl Documentation, and it's here to introduce Perl::Critic::Policy::InputOutput::ProhibitReadlineInForLoop. The whole policy vibe is: write while( $line = <> ){...} instead of for(<>){...}. That's it. That's the mission. πŸ’…


✨ AFFILIATION ✨

This Policy is part of the core Perl::Critic distribution. So it's not some random side quest β€” it's in the main character lineup. πŸ‘‘


πŸ¦‹ DESCRIPTION πŸ¦‹

Using the readline operator in a for or foreach loop is very slow. Like, not the vibe at all. 😭

Why? The iteration list of the loop creates a list context, which causes the readline operator to read the entire input stream before iteration even starts. The way that whole input stream gets slurped before the loop even begins? Not it, bestie.

Instead, just use a while loop, which only reads one line at a time. Slay. 🌈

for my $line ( <$file_handle> ){ do_something($line) }      #not ok
while ( my $line = <$file_handle> ){ do_something($line) }  #ok
The vibe check: for(<>){...} is giving β€œread everything first,” and while( $line = <> ){...} is giving β€œone line at a time, no drama.” The second one ate. πŸ”₯

πŸŽ€ CONFIGURATION πŸŽ€

No extra knobs, bestie: this Policy is not configurable except for the standard options. That's it. That's the config. 🫢


πŸ’– AUTHOR πŸ’–

Shoutout to the author: Jeffrey Ryan Thalhammer <jeff@imaginative-software.com> ✨


Copyright (c) 2005-2011 Imaginative Software Systems. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the LICENSE file included with this module. 🌸


okay bye bestie πŸ’… this page is from perl v5.42.0, dated 2024-10-23. Mwah. πŸ“

πŸ“¦ where this page comes from