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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

error when printing to the screen

Status
Not open for further replies.

dpimental

Programmer
Joined
Jul 23, 2002
Messages
535
Location
US
I am using the following code

Code:
sub replace {
   local $^I   = '.bak';
   my $find    = quotemeta(shift) or return(0);
   my $replace = shift or return(0);
   local @ARGV = shift or return(0);;
   while(<>){
      s/$find/$replace/;
      print;
   }
   close;
   return(1);
}

once I call this sub procedure, when I try to print something to the screen such as ...

Code:
print "working on folder " . $folder . "\n";

it doesn't work. My script only does the print statements to the screen that are before the sub procedure is called. If I put warnings on, it says that I am trying to print to a filehandle that has been closed.

Any help?

David Pimental
(US, Oh)
 
Yes, remove the random "close" statement from your sub. This should fix your problem.

- Miller
 
Not sure if this will work, but give it a try:

print STDOUT "blah blah blah";

or you might need to use select() to switch between STDOUT and the current filehandle in <>, which I think is called ARGV when you use @ARGV and <> to edit a file.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Yes, remove the random "close" statement from your sub. This should fix your problem.

DOH! Next time, I promise, I will look at the code. [wink]

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
I will give that a try.

Thanks !

David Pimental
(US, Oh)
 
It worked. But can someone explain why it worked.

Typically, when you open a file handle you have to close it.

Why didn't we need to close the file and why did removing it fix my problem.

David Pimental
(US, Oh)
 
You never opened a file handle. Instead, you used the shortcut technique for processing files passed as command line parameters and saving backups. When you start the while loop "while (<>)" perl automatically opens the input and output file handles for you. Similarly, when the while loop ends, perl also closes all those file handles that it opened.

When you called close, you were closing the default file handle at that time. Which because the while loop had ended was once again STDOUT.

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top