steve
steve

Reputation: 290

declaring global perl subroutines or global aliases

my question is, HOPEFULLY simple.

In Perl, how does one create a global scoped subroutine accessible to all objects thereafter?

sub throw
{
    die(shift);
}

Seems to work in global scope, but is not accessible to packages afterwards. I would like to avoid doing something of the sort of declaring that in every object in my application stack.

Side solution: How does one create an alias to a global keyword like die?

Please note: I do not really care if doing something like this is considered best practice. Although they perform the same function in Perl, die is not throw, and throw is not die. The following syntax does not follow the OOP principles that I am trying to follow:

die new Exception($message);

However logically similar, for the purpose of throwing exceptions, I would prefer the syntax of:

throw new Exception($message);

Many thanks to the stackoverflow community!

Upvotes: 1

Views: 63

Answers (2)

Dondi Michael Stroma
Dondi Michael Stroma

Reputation: 4800

What about a paradigm such as this, which would solve both your issues at once?

package Exception;

sub throw {
  my $message = shift;
  die Exception->new($message);
}

sub new {
  # whatever
}

...

And then in any package you can use it thusly:

package SomeClass;

sub do_something {
  ...
  if ($error) {
    Exception->throw($message);
  }
}

Upvotes: 1

choroba
choroba

Reputation: 241998

You can add throw to the UNIVERSAL package (which isn't a good practice).

Note that your throw ignores the message and displays just the class name.

#!/usr/bin/perl
use warnings;
use strict;

{   package UNIVERSAL;

    sub throw { die shift }
}

{   package MyClass;

    sub new { bless {}, shift }
}

my $c = 'MyClass'->new;
$c->throw('Ouch!');

See Try::Tiny.

Upvotes: 2

Related Questions