[Novalug] perl exiting loop question

Valdis Grinbergs v.grinbergs@verizon.net
Wed Aug 10 19:55:39 EDT 2011

In Perl, one usually reads in a file one line at a time, but a specific
number of bytes can also be read.  Below is an example program which
works without error using Perl v5.10.1.  Please post to novalug if you
find another interesting way to do this.
use strict;
use warnings;

my $fh_in;
my $fh_out;
my $bytes_read = 1;
my $buffer;

open $fh_in, '<', 'data_file' or die "could not write to data_file:$!
open $fh_out, '>', 'data_out' or die "could not write to data_out:$!\n";
while ($bytes_read > 0) {
    $bytes_read = read($fh_in, $buffer, 262144);
    # 2**18 bytes read into $buffer
    # data_file is a length that is deliberately not an even
    # multple of $buffer.  No error will occur, even if the
    # last buffer is not full.
    print $fh_out "$buffer\n";

You can test this program after running the following program to get
some dummy data.
use strict;
use warnings;

my $fh;
my $i = 0;

open $fh, '>', 'data_file' or die "could not write to data_file:$!\n";
while ($i < 400000) {
    print $fh '10';

On Sat, 2011-08-06 at 00:47 -0400, Bonnie Dalzell wrote:
> i have a loop in a program that, using a while loop,
> reads data from a large file of unknown length in 256k bytes chunks and 
> then within the loop does stuff to the data and saves it out to another 
> open out file.
> this works until I run out of input. then the program exits with an 
> error:
> "substr outside of string at libs/get_record.lib line 160"
> when it exits the file the data is being written into is properly 
> closed by the program exiting.
> however what I would like to have the program do is to exit the while loop 
> when the error appears without the program closing down.
> i have tried stuff like this:
>     while ($@ =~m/outside of string/){
>       actions---
>     }
> but this exits the loop immediately
> enlightenment and suggestions sought.
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>                         Bonnie Dalzell, MA
> mail:5100 Hydes Rd PO Box 60, Hydes,MD,USA 21082-0060|EMAIL:bdalzell@qis.net
> Freelance anatomist, vertebrate paleontologist, writer, illustrator, dog
> breeder, computer nerd & iconoclast... Borzoi info at www.borzois.com.
> HOME www.batw.net    ART bdalzellart.batw.net  BUSINESS www.boardingatwedge.com
> _______________________________________________
> Novalug mailing list
> Novalug@calypso.tux.org
> http://calypso.tux.org/mailman/listinfo/novalug

More information about the Novalug mailing list