Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^5: Track open file handles

by salva (Canon)
on Apr 07, 2017 at 08:57 UTC ( [id://1187381]=note: print w/replies, xml ) Need Help??


in reply to Re^4: Track open file handles
in thread Track open file handles

In order to avoid the wrong caller package issue, you can create a wrapping sub for open in the caller package and jump there using goto &$sub which overwrites the current stack frame. Something similar to the following code:
package MyOpen; use Carp (); use Data::Dumper; use 5.010; my %cache; BEGIN { *CORE::GLOBAL::open = sub { my $pkg = caller; my $sub = $cache{$pkg} //= do { my $code = <<EOS; package $pkg; sub { my \$r = CORE::open \$_[0], \@_[1..\$#_]; Carp::cluck(Data::Dumper::Dumper(\@_)); return \$r; } EOS eval $code or die "Bad sub: $@"; }; goto &$sub; }; } package main; open $fh, '>&', 'STDOUT'; open FOO, ">", "/tmp/FOO";

Replies are listed 'Best First'.
Re^6: Track open file handles
by shmem (Chancellor) on Apr 07, 2017 at 09:36 UTC

    Thank you. I was thinking about taking this road, using eval to switch package. I can't goto &$sub to erase the current stack frame, because I need to do the track housekeeping after the open, and record the (possible mutated) $_[0]. OTOH... thinking about it, I could switch package in that eval'ed sub again and do the housekeeping there. To that end, the %fh fieldhash must be a package var. Oh well.

    Currently, I am inspecting $_[0] with Devel::Caller etc. to find out whether the filehandle variable is lexical, package global, typeglob, bareword etc and trying to do the right thing. Anyways the overridden open would show up in the stack trace of Carp::cluck, so another stack frame wouldn't matter I guess. But with Sub::Name I could make that sub into the calling package. Maybe that's the best way to do it. It is definitely the cheapest in effort :-) update: and maybe the most robust also...

    Thanks again, salva!

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (8)
As of 2024-03-28 09:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found