William G. Davis has asked for the wisdom of the Perl Monks concerning the following question:
Hi again monks.
I need some help here with two file manipulation routines I'm working on. One is a routine that works just like open() under '>>' mode, only it flock()s the specified handle before returning. The other routine works like open() under '>' mode, only it flock()s the specified handle before clobbering it and then returns. Here are the two routines:
sub openFileForAppending(*$) { my $handle = qualify_to_ref(shift, caller);; my $name = shift; open($handle, '>> ' . $name) or return; attemptFlock($handle, LOCK_EX); return $handle; } ... sub openFileForWriting(*$) { my $handle = qualify_to_ref(shift, caller); my $name = shift; # If a file with that name exists, we'll open it for reading and # writing to prevent clobbering it prematurely before flock()ing i +t. # If we can successfully open it, then we'll try to flock() it, *t +hen* # we can safely clobber it: if (-e $name) { open($handle, '+< ' . $name) or return; attemptFlock($handle, LOCK_EX); seek($handle, 0, 0); truncate($handle, 0); } else { open($handle, '> ' . $name) or return; attemptFlock($handle, LOCK_EX); } return $handle; }
Now, the following works just fine:
openFileForWriting(TEST, 'test.txt'); print TEST "A test.\n"; close TEST;
But the following:
openFileForWriting(TEST, 'test.txt'); print TEST test(); close TEST; sub test { return "Another test.\n" }
Gives me:
Name "main::TEST" used only once: possible typo at listing6.pl line 10. Can't locate object method "TEST" via package "test" at listing6.pl line 9.
It appears what's happening here is that print TEST test() is being parsed as print test->TEST() (Perl's handy indirect object syntax) for some ungodly reason, yet if I replace the call to my special routine with a call to just plain-old open(), it works just fine. These two routines are defined in a module and exported by default. Is there anyway to get Perl to treat my open*() routines as it would the built-in open() in this respect?
Any help is appreciated.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Trouble making my own open()-like routines.
by blokhead (Monsignor) on Jul 07, 2004 at 06:19 UTC | |
by William G. Davis (Friar) on Jul 07, 2004 at 23:47 UTC | |
|
Re: Trouble making my own open()-like routines.
by davido (Cardinal) on Jul 07, 2004 at 06:21 UTC | |
by ysth (Canon) on Jul 07, 2004 at 15:30 UTC | |
by William G. Davis (Friar) on Jul 07, 2004 at 23:53 UTC |