A user on the DALnet #perl channel presented an interesting problem today. His CGI program was die'ing with the following exception:

Can't locate object method "new" via package "IO::Handle" (perhaps you + forgot to load "IO::Handle"?) at <line number>;

The indicated line number was the following attempt to invoke the class method &CGI::new:

my $q = new CGI;

I thought perhaps there was some ambiguity about the intent of the method invocation, so I suggested using

my $q = new CGI::;
to force perl to parse 'CGI' as a package name, but to no avail. After looking over the code for twenty minutes or so, I finally noticed that there were several open() statements that opened a filehandle named, you guessed it, 'CGI'. I guessed that CGI was being made an IO::Handle object at compile time, and that the subsquent attempt to invoke the &CGI::new class method was actually being interpreted as an IO::Handle instance method invocation against the non-existent method &IO::Handle::new.

As a test, I moved the invocation of the CGI:: constructor to a BEGIN block, and everything seemed to work as expected.

This demonstrates the problem:

$ perl -MCGI -e 'my $q = new CGI::; open CGI, "~/foo.txt";' Can't locate object method "new" via package "IO::Handle" (perhaps you + forgot to load "IO::Handle"?) at -e line 1.

The obvious workaround is to refrain from using filehandles with the same names as packages, but this is the first time I've run into this problem. I tested this in perl versions 5.005_03, 5.6.0 and 5.6.1, by the way.

Is this breakage in perl, or have I missed a big fat "don't do this!" somewhere in the POD?

conv


In reply to Filehandles vs. Packages: And the winner is... by converter

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.