in reply to Filling a File with While

I'm trying to fill a file until I hit a certain size

I'm wondering why you wouldn't just keep up a byte count of what gets written to the file:

my $bytes_written = 0; my $bytes_wanted = 2**30; # or whatever my $data = "Something...\n"; # set output content here... while (1) { # $data = ...; # ... or here print $fh $data; $bytes_written += length( $data ); last if $bytes_written >= $bytes_wanted; }
If you need to keep track in terms of block count, there would be a little more arithmetic involved (and correct background info about what the block size really is).

As indicated in another reply, you might need to be careful about whether length() is counting bytes or wide (utf8) characters.

UPDATED to fix stupid mistake in the "last if ..." line (needed to compare the right variable to $bytes_wanted).

Replies are listed 'Best First'.
Re^2: Filling a File with While
by aquarium (Curate) on Nov 06, 2008 at 02:42 UTC
    if you only need round about figures to stop the loop, you could even approximate the characters per line, and hence exit the loop based entirely on loop count.
    if you insist on lookup up file size, keep in mind that writing can be cached/buffered, and some system calls for filesystem info are cached unless a specific "full" system call is issued.
    the hardest line to type correctly is: stty erase ^H