[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] How files are read in (was: for loops)



At 09:01 AM 12/30/98 +0000, G. Ann Campbell wrote:
>
>When I did this:
>
>   open(OBITS,"$filename") || die "Can\'t open file\n";
>   @obits = <OBITS>;
>   close(OBITS);
[additional code snipped]
>
>It worked beautifully, making all the proper line for line substitutions. - So

>But when I did this:
>
>  open(TXT, "$ObitFile:class.txt") || die "Can\'t open text file for 
>reading\n";
>     $txt = <TXT>;
>     close (TXT);
[additional code snipped]
>
>It put the entire contents of the file into the first element of the list. I
>know now how to get around it, but I don't understand why.

Yep.  Take a look at these two snippets carefully.  The first one has
	@obits = <OBITS>;
which reads the contents of the file referenced by OBITS into the array
@obits, with each line of the file corresponding to an entry in the array,
in order.  The second snippet has
	$txt = <TXT>;
which reads the *first line* of the file referenced by TXT into the
*scalar* $txt, which then produces really interesting results when you
later try to use the array @txt, as you saw.  If the line endings in the
file referenced by TXT are not equivalent to the current value of $/ (or is
it $\...I can never remember without my Perl handbook around), then you
will actually get the entire file TXT stored in $txt, but as a single
string, and not as an array.

In other words (and I'm sure there's a more technical explanation of this,
but it usually isn't necessary), @list = <FILE> reads each portion (think
"line") of FILE that up to the current value of $/ into the corresponding
entry in @list.  Meanwhile, $scalar = <FILE> reads a single portion of FILE
up to the current value of $/ into $scalar.  Note that you can change how
those portions -- lines -- are defined by setting $/ to whatever is
appropriate, or undef'ing it if you want to read whole files into a scalar.

Hope this helps,
Eric

---------------------------------------------
Eric Albert          ejalbert@cs.stanford.edu
http://www.stanford.edu/~ejalbert/


***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch