in reply to OOP - Constant Vs. Subroutine

The constant pragma creates a sub with a specific prototype, allowing it to be in-lined. For some uses in OO code, you're probably better off using class methods, since subclasses can override them.

Replies are listed 'Best First'.
Re^2: OOP - Constant Vs. Subroutine
by 2xlp (Sexton) on May 11, 2007 at 21:46 UTC
    subclasses can override constants too.
      How would you do that? Would you have to call it like a method?
      Class->constant;
      That would prevent the in-lining behavior, but I guess it's no worse than a normally defined simple method.

        Not really, Class->constant won't inherit from Superclass->constant ; it needs to be defined in both.

        however $classObject->constant will inherit constants from superclass as class object methods , and allow the ability to override

        so...

        package aaa; use constant HELLO=> 'world'; use constant PUNCTUATION=> '!'; sub new { #std constructor here } package bbb; our @ISA= qw( aaa ); use constant HELLO=> 'universe'; package main; my $a= aaa->new(); my $b= bbb->new(); print "\n Hello " . $a->HELLO . $a->PUNCTUATION ; print "\n Hello " . $b->HELLO . $b->PUNCTUATION ;

        will get you

        Hello world! Hello universe!

        but bbb->PUNCTUATION doesn't exist