Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Reading a line from a Temporary File

by dReKurCe (Scribe)
on Jul 31, 2005 at 20:21 UTC ( [id://479733]=perlquestion: print w/replies, xml ) Need Help??

dReKurCe has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks:

I am atempting to open a temporary file <TMP> using File::Temp. The goal is to to write the contents of  $page to the temp file.Next I would like to write a conditional statement that is dependant upon an regex.When the regex is finished reading I want the temp file to disappear.


The following code looked to me like it might do the right thing however, the while (<TMP>) loop seems uneffective.

Guidance Appreciated
sub captured{ my ($page,$addy) =shift @_; use File::Temp qw(tempfile unlink0 ); use vars qw($fh $filename); my $template = 'tempXXXXXXXXXX'; my $dir = '/tmp/'; ($fh, $filename) = tempfile($template, DIR => $dir) or die " Error creating $filename: $!"; print "\nCreated file $filename.\n"; open (TMP, "+< $filename") or die "Error opening $filename for WO: $!"; print TMP "$page" or die "Error writing to $filename: $!"; while (<TMP>){ my $header=$_; print "$header"; #if ($header=~/^\<TITLE\>Target String Here\<\/TITLE\>$/){ print "$addy is a page of interest\n"; } close (TMP) or die "Error closing $filename: $!"; unlink0 ($fh, $filename) or die "Error unlinking file $filename safely: $!"; }

Replies are listed 'Best First'.
Re: Reading a line from a Temporary File
by Joost (Canon) on Jul 31, 2005 at 20:29 UTC
    If the whole content of the page is already in $page, I can't see much use for using a temporary file; you can just run the regex against $page directly.

    I think your immediate problem can be resolved by "rewinding" the filehandle before reading (it's positioned at the end of the file when you've written $page to it).

    Doing seek TMP,0,0; before the while (<TMP>) line should take care of that.

    See seek.

      Amazing solution! Thank you!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://479733]
Approved by Joost
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2024-04-25 05:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found