Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

slurping files quickly

Status
Not open for further replies.

kaih

Programmer
Dec 7, 1999
26
US
<br>
Is there a one line way to slurp a file into an array?<br>
<br>
Instead of <br>
open(FILE, &quot;file&quot;) ¦¦ warn &quot;couldn't open file&quot;;<br>
@array = &lt;FILE&gt;;<br>
close(FILE);<br>
<br>
I would like to <br>
@array = &lt;&quot;file&quot;&gt;;<br>
<br>
I know, it's just a couple of lines, but Larry Wall himself says that lazyness is a virtue. :)<br>
<br>
I saw someone do this:<br>
@array = `/bin/cat file`;<br>
<br>
but I want to stay in perl.<br>
<br>
Thanks!<br>
- Kai.<br>

 
For quick and dirty, it seems like 'cat' is a very reasonable way to do this.... unless you are interested in controlling the child process .... or .....you want to make the code portable to other OS's which might not have 'cat'....like a M$ windows PC.... ( which is available from Cygwin).
 
Don't think you'd be able to do this, the reason being that you have to open the file before you can read it. No way around it (that I'm aware of). One way of simulating what you want would be to create a subroutine along the lines of:<br>
<br>
sub slurp {<br>
my $Filename = $_[0];<br>
my @File_Array;<br>
open(MYFILE, &quot;&lt;$Filename&quot;);<br>
@File_Array = &lt;MYFILE&gt;;<br>
close(MYFILE);<br>
return(@File_Array);<br>
}<br>
<br>
Then call it as:<br>
<br>
@File_Stuff = slurp(&quot;/path/to/my/file&quot;);
 
Yeah, that's kind of what I thought. Be handy if it were built in, but I guess I'll make a module similar to what you wrote. Thanks.
 
The line...<br><br>@file = &lt;ARGV&gt;;<br><br>will actually slurp the contents of a filename passed in as a parameter without requiring that you open the file.&nbsp;&nbsp;So, if you call the above line 'slurp.pl' and start the script as such...<br><br>perl slurp.pl test.txt<br><br>the entire contents of test.txt will be slurped into @file, even though you didn't explicity open it.<br><br>Strange, but true.<br>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top