in reply to Range question

In scalar context, it's usually called the flip-flop operator.

What it's doing is printing all the lines that contains *end* and all the lines containing *start*, and every line in between. If *start* or *end* occurs in the middle of a line, so be it. If multiple *start* or *end* tags exist in one line, so be it.

The whole concept of line is kinda odd when dealing with binary data anyway. Usually one reads fixed-width blocks of data when dealing with binary data because you'll never know how long a line will be. (0 bytes? 1 bytes? the entire file?)

Assuming fixed-width delimiters, your code should look like this:

#!/usr/bin/perl -w use strict; use constant BLK_SIZE => 64*1024; sub process { my ($data) = @_; print($data); # Or whatever } sub read_more { my $fh = shift; my $rv = read($fh, $_[0], BLK_SIZE, length($_[0])); die $! if !defined($rv); return $rv; } my $start = '*start*of*junk*data*'; my $end = '*end*of*junk*data*'; my $qfn = "file"; open( my $fh, '<:raw:perlio', $qfn ) or die("open $qfn: $!\n"); my $buf = ''; my $in_junk = 0; while (read_more($fh, $buf)) { if ($in_junk) { my $pos = index($buf, $start); if ($pos >= 0) { process(substr($buf, 0, $pos, '')); substr($buf, 0, length($start), ''); $in_junk = 1; redo; } else { process(substr($buf, 0, -length($start)+1, '')); } } else { my $pos = index($buf, $end); if ($pos >= 0) { substr($buf, 0, $pos+length($end), ''); $in_junk = 0; redo; } else { substr($buf, 0, -length($end)+1, ''); } } } process($buf) if !$in_junk;

Replies are listed 'Best First'.
Re^2: Range question
by ikegami (Patriarch) on Apr 10, 2009 at 04:02 UTC

    Assuming constant delimiters, a simpler solution:

    #!/usr/bin/perl -w use strict; sub process { my ($data) = @_; print($data); # Or whatever } my $start = '*start*of*junk*data*'; my $end = '*end*of*junk*data*'; my $qfn = "file"; open( my $fh, '<:raw:perlio', $qfn ) or die("open $qfn: $!\n"); for (;;) { $/ = $start; my $good = <$fh>; last if !defined($good); chomp($good); process($good); $/ = $end; my $junk = <$fh>; last if !defined($junk); }