atom feed3 messages in org.perl.beginnersRe: reflection in perl
FromSent OnAttachments
Michael SeeleOct 7, 2004 2:28 am 
Paul JohnsonOct 7, 2004 3:32 am 
Todd WOct 9, 2004 12:46 pm 
Subject:Re: reflection in perl
From:Todd W (send@hotmail.com)
Date:Oct 9, 2004 12:46:43 pm
List:org.perl.beginners

"Michael Seele" <mse@guh-software.de> wrote in message news:4165@guh-software.de...

hi, i'm new to perl and i want to know if perl has reflection like java? how can i acces reflection and how powerfull is the reflection in perl? thx mseele

Perls reflection support is probably my most favorite thing about perl. Basically, reflection is built in to perl. No reflection API is needed. You just use scalar variables that contain class and method names in place of the actual names and everything works dynamically:

use warnings; use strict;

package Base;

sub new { my $class = shift(); my $self = bless( { }, $class ); return( $self ); }

our $line = 1; sub print { my $class = shift(); print( $line, ': ', @_, "\n" ); $line++; }

sub foo { my $proto = shift(); $proto->print('Hello from ', (ref($proto) or $proto), '->foo'); }

sub bar { my $proto = shift(); $proto->print('Hello from ', (ref($proto) or $proto), '->bar'); }

package ClassA; use base qw/Base/;

sub foo { my $proto = shift(); #do work specific for this class, then... $proto->SUPER::foo(); }

sub bar { my $proto = shift(); #do work specific for this class, then... $proto->SUPER::bar(); }

package ClassB; use base qw/Base/;

sub foo { my $proto = shift(); #do work specific for this class, then... $proto->SUPER::foo(); }

sub bar { my $proto = shift(); #do work specific for this class, then... $proto->SUPER::bar(); }

package main;

foreach my $class ( qw/ClassA ClassB/ ) { my $obj = $class->new(); foreach my $method ( qw/foo bar baz/ ) { if ( $obj->can( $method ) ) { $obj->$method(); } else { $class->print("$obj cant $method"); } } }

output:

1: Hello from ClassA->foo 2: Hello from ClassA->bar 3: ClassA=HASH(0x15d5218) cant baz 4: Hello from ClassB->foo 5: Hello from ClassB->bar 6: ClassB=HASH(0x1a8941c) cant baz