Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hi, Let's say I have file such as below which contains no pattern in any lines.
I want to treat every 3 lines as input record separator and I thought I could do this
$/ = ".*\n.*\n.*\n"
But I am not getting desired output. Am I missing something?
-- file -- asdfasdf asdfasdf asdfasdf asdfasdfasdf asdfasdf someting adfasdf asdfasdfasdfasdfasdf asdfasdfasdf asdfasdfasdfasdfasdfasdf werwerwerwer ertertert zsdfasdfasdf

Replies are listed 'Best First'.
Re: input record separator
by toolic (Bishop) on Jun 01, 2010 at 01:56 UTC
    From the docs for $/:
    Remember: the value of $/ is a string, not a regex.
    Your .* are regular expression syntax, but they are treated as a literal dot followed by a literal asterisk when assigned to the input record separator special variable.

    If you want to avoid slurping your entire file into memory at once, you could operate on 3 lines at a time by creating a 3-line buffer:

    use warnings; use strict; my @lines; while (<>) { push @lines, $_; if ($. % 3 == 0) { # do something with @lines; @lines = (); } }
      my @lines; while (<>) { push @lines, $_; next if $. % 3; ... @lines = (); } die if @lines;
      can also be written as
      while (!eof()) { my @lines; defined( $lines[@lines] = <> ) or die for 1..3; ... }
Re: input record separator
by Marshall (Canon) on Jun 01, 2010 at 08:38 UTC
    Or just perhaps:
    #!/usr/bin/perl -w use strict; while (<DATA>) { my $three_lines = $_.<DATA>.<DATA>; print $three_lines, "\n"; } =output asdfasdf asdfasdf asdfasdf asdfasdfasdf asdfasdf someting adfasdf asdfasdfasdfasdfasdf asdfasdfasdf asdfasdfasdfasdfasdfasdf werwerwerwer ertertert zsdfasdfasdf =cut __DATA__ asdfasdf asdfasdf asdfasdf asdfasdfasdf asdfasdf someting adfasdf asdfasdfasdfasdfasdf asdfasdfasdf asdfasdfasdfasdfasdfasdf werwerwerwer ertertert zsdfasdfasdf
Re: input record separator
by wwe (Friar) on Jun 01, 2010 at 09:24 UTC
    Take a look at Perl6::Slurp which is a back-port of Perl6 slurp built-in and accepts regex for input record separator.
    # Specify input record separator... $file_contents = slurp $file, {irs=>"\n\n"}; $file_contents = slurp '<', $file, {irs=>"\n\n"}; $file_contents = slurp {irs=>"\n\n"}, $file;