Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
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
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 studying the Monastery: (7)
As of 2014-09-21 10:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (168 votes), past polls