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

Re^2: Foo->new() vs. new Foo()

by shemp (Deacon)
on Oct 24, 2005 at 18:46 UTC ( [id://502554]=note: print w/replies, xml ) Need Help??


in reply to Re: Foo->new() vs. new Foo()
in thread Foo->new() vs. new Foo()

Calling Foo::new() calls the function new in the package Foo as a direct function call. It doesn't magically put the class name in the first element of @_ in Foo::new(). The call is completely different. This example will show that:
# this is the file Foo.pm package Foo; use strict; use warnings; sub new { my $class = shift @_; print "class = $class\n"; my $self = {}; return bless $self, $class; } 1; # heres a test program using it, called foo_test.pl # #!/usr/bin/perl use strict; use warnings; use Foo; use Data::Dumper; { print "Arrow test:\n"; my $regular_foo = Foo->new(); print Dumper($regular_foo); print "\n\nColon test:\n"; my $colon_foo = Foo::new(); print Dumper($colon_foo); }
And heres the output from running foo_test.pl
Arrow test: class = Foo $VAR1 = bless( {}, 'Foo' ); Colon test: Use of uninitialized value in concatenation (.) or string at Foo.pm li +ne 9. class = Use of uninitialized value in bless at Foo.pm line 13. Explicit blessing to '' (assuming package main) at Foo.pm line 13. $VAR1 = bless( {}, 'main' );
I use the most powerful debugger available: print!

Replies are listed 'Best First'.
Re^3: Foo->new() vs. new Foo()
by NetWallah (Canon) on Oct 24, 2005 at 21:36 UTC
    To allow the caller to use the Foo::new() syntax, the sub could be coded thus:
    sub new { my $class = shift @_ || __PACKAGE__; ... }
    This gives the same result as calling using the Foo->new syntax.

         "Man cannot live by bread alone...
             He'd better have some goat cheese and wine to go with it!"

      Aside from breaking inheritance, why would you want to do that?

      Sub::new(1);

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-19 02:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found