in reply to Class / package weak association

> If a blessed object kept track of whether it was associated with a package of that name, and the information went into the Dumper output, then when the string was evaled, if there was no package of the right name loaded, it could point that out (optional extra parameter to bless, or something?).

OK if you only want to be warned if the package doesn't exist, you can also override bless locally inside a package to do the check for you.

please note that blessing will autovivify the class, i.e. the package TST1:: will "exist".

use strict; use warnings; use Data::Dumper; my $obj = bless {}, "TST1"; my $str1 = Dumper $obj; my $str2 = q($VAR1 = bless( {}, 'TST2' );); package Bless::Safe; use subs qw/bless/; sub bless ($;$) { my ($obj,$class) = @_; die "Can't bless into non-existent Package $class" unless exists $main::{"${class}::"}; } our $VAR1; eval($str1) or $@ && die $@; # OK eval($str2) or $@ && die $@; # FAILS

HTH! :)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

updates

  • fixed bug in $@ check
  • added prototype
  • Replies are listed 'Best First'.
    Re^2: Class / package weak association
    by dd-b (Pilgrim) on Jun 10, 2021 at 21:32 UTC

      Yeah, I already saw issues with attempting to really package the class as part of the stringification (all sorts of issues, many already mentioned here, both in general and in my particular use); I was just a little surprised not to be warned that I'd neglected to use the package.

      I was thinking about adding a new function call to do eval-with-bless-checking, hadn't realized I could actually overload bless to verify the package. I don't do any blessing without packages that I remember in this code, so that might be a clean way to fix that.

      At least I've learned something new (didn't realize I could override bless!). I shouldn't be surprised, at this point there's not all that much I can't override in Perl.

        > At least I've learned something new (didn't realize I could override bless!). I shouldn't be surprised, at this point there's not all that much I can't override in Perl.

        Please note that it's not global but "only" on package basis, which is a good thing. Better don't try this in main.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery