Two problems.
-
First, as the warning indicates, the main::open in
*{main::open} = sub { print "Ho\n"; };
is interpreted as a call to open. (Upd: Not sure how it's being interpreted anymore, but it's definitely not working as expected. ) You want
my $glob_ref = do { no strict 'refs'; \*{'main::open'} };
*$glob_ref = sub { print "Ho\n"; };
-
Second, you delude yourself by putting the use subs at the bottom.
BEGIN {
# Deleting and remaking the sub fails! ;(
delete $main::{open};
*{main::open} = sub { print "Ho\n"; };
use subs 'open';
}
means
BEGIN {
# Deleting and remaking the sub fails! ;(
delete $main::{open};
*{main::open} = sub { print "Ho\n"; };
BEGIN {
require subs;
import subs 'open';
}
}
which is compiled and executed as follows:
- "delete $main::{open};" is compiled.
- "*{main::open} = sub { print "Ho\n"; };" is compiled.
- "require subs;" is compiled.
- "import subs 'open';" is compiled.
- "require subs;" is executed. (The inner BEGIN is executed as soon as it's compiled.)
- "import subs 'open';" is executed.
- "delete $main::{open};" is executed. (The outer BEGIN is executed as soon as it's compiled.)
- "*{main::open} = sub { print "Ho\n"; };" is executed.
"import subs 'open';" should not be executed before "delete $main::{open};".
Fixed:
use strict;
use warnings;
use subs qw( );
open(my $fh, '<', $0); # Calls CORE::open
BEGIN {
my $glob = do { no strict 'refs'; \*{'main::open'} };
*$glob = sub { print "Hi\n"; };
import subs 'open';
}
open(my $fh2, '<', $0); # Prints Hi
BEGIN {
delete $main::{open};
my $glob = do { no strict 'refs'; \*{'main::open'} };
*$glob = sub { print "Ho\n"; };
import subs 'open';
}
open(my $fh4, '<', $0); # Prints Ho
BEGIN {
delete $main::{open};
}
open(my $fh5, '<', $0); # Calls CORE::open
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|