Thursday, January 27, 2011

Read a line from a file or the hole content of the file

test.txt file has 2 lines:  
-first line
-second line


1. Read a single line
open FILEHANDLE, 'test.txt' or die $!;
$string = <FILEHANDLE>;


Result: $string will contain "-first line"


2. Read the hole file

2.1 First Option
open FILEHANDLE, 'test.txt' or die $!;
undef $/;    # whole file
$string = <FILEHANDLE>;

# $/ is the input record seperator, is used to modify the behavior of how many records are read in when you use the diamond operators like <FILEHANDLE>. If $/ is set to undef, then accessing <FILEHANDLE> in scalar context will grab everything until the end of the file

2.2 Second Option
open FILEHANDLE, 'test.txt' or die $!;
$string = do { local $/; <FILEHANDLE> };

2.3 Third Option

open FILEHANDLE, 'test.txt' or die $!;
@array  = <FILEHANDLE>;


Result for 2.1, 2.2 and 2.3 is the same: $string will contain the hole file
-first line
-second line

No comments:

Post a Comment