in reply to anonymous filehandle for overridden open sub

Surprisingly, no one managed to hit the reason why this fails. In your original code, $filehandle is referencing a global glob. With your new code, $filehandle is now ... undef. So CORE::open looks at your old code, gets the string, and populates that glob, while with the new code, it gets the reference to $filehandle and updates it.

$filehandle is now its own copy of undef, rather than a reference to it. So update your code like this:

use strict; sub open { # log stuff here. CORE::open(@_); } if (-e $0 and open(my $fh, '<', $0)) { while(<$fh>) { print; } }
Works fine. The key point is not to shift off the reference to your caller's parameters so that you can continue to update them. Your logging stuff that is happening probably will need some changes (to stop referencing $filehandle, and all the array indexes are changing by one), but this should allow the new overridden open to work with both your updated code and your old-style code (with globs).

Update: No changes to the above, but to address ysth's comment, all I know is that I tested the above code prior to posting, and it printed itself out. Perl 5.8.6. YMMV.

Replies are listed 'Best First'.
Re^2: anonymous filehandle for overridden open sub
by ysth (Canon) on Apr 07, 2005 at 21:38 UTC
    open's prototype makes just passing @_ not work. See tilly's answer for the way to do this.

    Update: well, I was so sure the above wouldn't work that I didn't even try it...so I wasn't misled by the apparent success. Because Tanktalus's code doesn't use warnings, he/she is missing this:

    Ambiguous call resolved as CORE::open(), qualify as such or use &
    So in fact the sub never even gets called. To call a sub with the same name as a builtin, you need to specify & (or have actually overriden the builtin as described in perlsub). Modifying the code to say &open(my $fh.... gives the error I was cautioning about:
    Can't use string ("3") as a symbol ref while "strict refs" in use
    due to the scalar prototype on open's first argument. (@_ == 3).
Re^2: anonymous filehandle for overridden open sub
by tlm (Prior) on Apr 07, 2005 at 22:38 UTC

    Surprisingly, no one managed to hit the reason why this fails.

    Sorry for tooting my own horn here, but some of us did :-) .

    In your original code, $filehandle is referencing a global glob. With your new code, $filehandle is now ... undef.

    Therefore, give the overriding open a non-undef lexical handle instead: open(my $AFILE = IO::File->new(), ... ). This solution has the virtue that it does not require that the overriding open be modified, something that may not be possible or desirable.

    the lowliest monk