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

I have a large text file which is only one line. It is too big to read all at once. Is there any way to do single character input from a file? Thanks, Michael

Replies are listed 'Best First'.
Re: Character Input
by japhy (Canon) on Mar 27, 2000 at 21:59 UTC
    You can use the getc() function on a filehandle:
    open FILE, "file" or die "can't read file: $!"; $char = getc FILE; close FILE;
    You can set $/ to a reference to 1:
    open FILE, "file" or die "...: $!"; { local $/ = \1; $char = <FILE>; } close FILE;
    Or use read() or sysread():
    open FILE, "file" or die "yeah, $!"; read FILE, $char, 1; # or sysread FILE, $char, 1; close FILE;
    Any additional error checking is an exercise to the reader.
Re: Character Input
by httptech (Chaplain) on Mar 27, 2000 at 17:00 UTC
    If your file is delimited by any particular character or sequence of characters, you could redefine the special variable $/ to something other than the default newline character. For example, to read a single line one word at a time:
    { local $/ = ' '; while (<>) { print } }
Re: Character Input
by btrott (Parson) on Mar 27, 2000 at 09:24 UTC
    open S, "foo" or die "Can't open foo: $!"; my $buffer; while (read S, $buffer, 1) { print $buffer, "\n"; } close S or die "Can't close foo: $!";
    Though you may want to read in slightly larger increments than one character at a time, as that's relatively slow.

    How large is your file? Perhaps reading in 4k bytes at a time might work out for you?

      It is worth noting that speed will probably not be a problem with this since Perl's stdio is buffered by default.

      That is, the first call to read() will cause Perl to stash away its own buffer, preventing you from needing to maintain your own.

      If you want to do it this way, sysread() would be a better choice, as this is Perl's interface to the read() syscall.

Re: Character Input
by coolmichael (Deacon) on Mar 29, 2000 at 09:19 UTC
    Thank you very much. All your suggestions worked quite well. For anyone interested, the file contains the first 10 million digits of pi (11.4 Mb, uncompressed ascii). Thanks again.