I saw some code that uses the subs pragma to override perl's open function. I thought that would be a handy trick to know, so I tried a simple example:
use subs 'open';
sub open
{
print "opening file: @_\n";
CORE::open(@_);
}
That didn't work for me, but when I changed the CORE::open line to the following, it did work:
CORE::open($_[0], $_[1]);
Any idea why that makes a difference?
Here's a little script that demonstrates the difference:
Given just an argument of "test.txt", it works. But if I run it with args of "test.txt bad", it fails. $! is empty even when it fails.
use subs 'open';
$file = $ARGV[0];
$method = $ARGV[1] eq 'bad' ? 0 : 1;
sub open
{
my $count = scalar @_;
print "opening file: @_ ($count)\n"; # Prints "opening file: TEST
+ [filename] (2)" for either method
my $return;
if ($method == 0)
{
$return = CORE::open(@_); # doesn't work
}
else
{
$return = CORE::open($_[0], $_[1]); # works
}
return $return;
}
if ($result = open (TEST, $file))
{
my $lineCount;
for my $line (<TEST>)
{
last if $lineCount++ > 5;
print "$line\n";
}
close TEST;
}
else
{
print "couldn't open test.pl\n";
print "error info: $!\n" if $!;
print "more error info: $^E\n" if $^E;
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.