raflach has asked for the wisdom of the Perl Monks concerning the following question:
OK, I know that I can set $/ = undef; to read in an entire file at one time, but what if I am reading in an unknown amount of data with an unknown terminator? I want to read in the data one character at a time, and use an alarm signal to catch when no more data is being received. My question is, "Can this be done?" I haven't been able to figure out how to set $/ to catch one character at a time. or some other way of reading off of a filehandle that will catch one character at a time.
Re: $/ question
by splinky (Hermit) on Jul 05, 2000 at 18:52 UTC
|
A little-known recent Perl enhancement is the ability to
read fixed-length records by setting $/ to a reference
to an integer.
So, in your case, you'd say $/ = \1
However, you mention something about no more data being
received, which leads me to believe you may be reading
the data as it's being written, such as from a pipe or
socket or something. If that's the case, you need to
check into non-blocking IO. Check out perlipc and
perlfaq8 for more info on such things.
*Woof* | [reply] [d/l] |
Re: $/ question
by c-era (Curate) on Jul 05, 2000 at 18:55 UTC
|
You can use sysread to read on character at a time.
while(sysread FILENAME,$char,1){
# ^
# length
# Do something with $char
}
| [reply] [d/l] |
Re: $/ question
by davorg (Chancellor) on Jul 05, 2000 at 19:02 UTC
|
Sounds like you need read. From perldoc -f read:
read FILEHANDLE,SCALAR,LENGTH
Attempts to read LENGTH bytes of data into variable
SCALAR from the specified FILEHANDLE. Returns the number
of bytes actually read, 0 at end of file, or undef if there
was an error. SCALAR will be grown or shrunk to the length actually read. An OFFSET may be specified to place the read data at some other place than the beginning of the
string. This call is actually implemented in terms of stdio's fread(3) call. To get a true read(2) system call, see sysread().
--
<http://www.dave.org.uk>
European Perl Conference - Sept 22/24 2000, ICA, London
<http://www.yapc.org/Europe/>
| [reply] |
Re: $/ question
by lhoward (Vicar) on Jul 05, 2000 at 19:10 UTC
|
All these techniques for reading one character at a time
will work, but may be slow. You may be better reading in a
large block of
characters at a time and stripping them off one-at-a-time. | [reply] |
|
Just to give a little code to show what lhoward is saying
my $length = 1000;
read (FILEHANDLE, my $varWithChar, $length);
my @array = split //, $varWithChar;
foreach (@array){
#do stuff with $_
}
--BigJoe
| [reply] [d/l] |
Re: $/ question
by raflach (Pilgrim) on Jul 05, 2000 at 20:48 UTC
|
Thanks to all... These worked, and answered my question although they didn't solve my problem. "splinky" was right... This is an IPC issue, using what I originally supposed to be non-blocking solution... namely Open2. See my new question in SOPW. | [reply] |
|