Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Read File In Four-Line Chunks / TMTOWTDI / Golf

by Aristotle (Chancellor)
on Jun 06, 2003 at 11:45 UTC ( #263641=note: print w/ replies, xml ) Need Help??


in reply to Read File In Four-Line Chunks / TMTOWTDI / Golf

My first thought:

#!/usr/bin/perl -w use strict; open my $fh, '<', 'details.txt' or die $!; until(grep !defined, my @details = map scalar <$fh>, 1 .. 4) { print @details, "\n"; }
A C programmer's well trained reflex:
#!/usr/bin/perl -w use strict; open my $fh, '<', 'details.txt' or die $!; my $i; my @details; while(<$fh>) { push @details, $_; next if ++$i % 4; print @details, "\n"; @details = (); }
A LISP hacker's immediate reaction:
#!/usr/bin/perl -w use strict; open my $fh, '<', 'details.txt' or die $!; sub read_lines { my ($fh, $amnt) = @_; return unless defined(my $line = <$fh>); return ( $line, $amnt > 1 ? read_lines($fh, $amnt - 1) : () ); } while(my @details = read_lines($fh, 4)) { print @details, "\n"; }

Makeshifts last the longest.


Comment on Re: Read File In Four-Line Chunks / TMTOWTDI / Golf
Select or Download Code
Replies are listed 'Best First'.
Re^2: Read File In Four-Line Chunks / TMTOWTDI / Golf (more)
by Aristotle (Chancellor) on Jun 06, 2003 at 14:55 UTC
    Some further perversions of the LISPish way:
    #!/usr/bin/perl -w use strict; open my $fh, '<', 'details.txt' or die $!; my $read_lines; while( my @details = ($read_lines = sub { my $amnt = shift; return unless defined(my $line = <$fh>); return ( $line, $amnt > 1 ? $read_lines->($amnt - 1) : () ); })->(4) ) { print @details, "\n"; }
    Refined perversion:
    #!/usr/bin/perl -w use strict; sub make_read_lines { my ($fh, $lines) = @_; return $lines == 1 ? sub { return unless defined(my $line = <$fh>); $line } : do { my $next_lines = make_read_lines($fh, $lines - 1); sub { return unless defined(my $line = <$fh>); $line, $next_lines->() }; }; } open my $fh, '<', 'details.txt' or die $!; my $read_4_lines = make_read_lines($fh, 4); while(my @details = $read_4_lines->()) { print @details, "\n"; }

    Makeshifts last the longest.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://263641]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (10)
As of 2015-07-29 08:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (261 votes), past polls