Prev: deleting subjects
Next: Proc Import Excel Range
From: xlr82sas on 17 Mar 2010 14:25 Hi SAS-lers, I hope SAS-Lers do not take my intentions the wrong way. My goal would be to enhance SAS by integrating perl. SAS is like the universe of light and perl and R are like the world of sound. Sound cannot travel past the earths atmosphere but light is can travel through the universe. Interesting concept to read all lines of a file into and array and then access lines randomly. 5.28: perl How can I read in an entire file all at once? $ - scaler @ - array You can use the File::Slurp module to do it in one step. use File::Slurp; $all_of_it = read_file($filename); # entire file in scalar @all_lines = read_file($filename); # one line per element The customary Perl approach for processing all the lines in a file is to do so one line at a time: open (INPUT, $file) || die "can't open $file: $!"; while (<INPUT>) { chomp; # do something with $_ } close(INPUT) || die "can't close $file: $!"; This is tremendously more efficient than reading the entire file into memory as an array of lines and then processing it one element at a time, which is often--if not almost always--the wrong approach. Whenever you see someone do this: @lines = <INPUT>; you should think long and hard about why you need everything loaded at once. It's just not a scalable solution. You might also find it more fun to use the standard Tie::File module, or the DB_File module's $DB_RECNO bindings, which allow you to tie an array to a file so that accessing an element the array actually accesses the corresponding line in the file. You can read the entire filehandle contents into a scalar. { local(*INPUT, $/); open (INPUT, $file) || die "can't open $file: $!"; $var = <INPUT>; } That temporarily undefs your record separator, and will automatically close the file at block exit. If the file is already open, just use this: $var = do { local $/; <INPUT> }; For ordinary files you can also use the read function. read( INPUT, $var, -s INPUT ); The third argument tests the byte size of the data on the INPUT filehandle and reads that many bytes into the buffer $var.
|
Pages: 1 Prev: deleting subjects Next: Proc Import Excel Range |