liz has asked for the wisdom of the Perl Monks concerning the following question:
Some background: the forks::shared module already had a "_share" subroutine that only needs a reference to the variable (either a scalar, array or hash) to be shared. This subroutine basically does a tie on the variable.
sub _share { my $it = shift; my $ref = ref $it; if ($ref eq 'SCALAR') { tie ${$it},'threads::shared',{},${$it}; } elsif ($ref eq 'ARRAY') { tie @{$it},'threads::shared',{},@{$it}; } elsif ($ref eq 'HASH') { tie %{$it},'threads::shared',{},%{$it}; } elsif ($ref eq 'GLOB') { tie *{$it},'threads::shared',{},*{$it}; } else { _croak( "Don't know how to share '$it'" ); } } #_share
So the attribute handler only needed to get the reference and act on that. No further attribute data needs to be kept.
Yesterday, I finally grokked attributes.pm, particularly this bit:
and created the following code:
BEGIN { no strict 'refs'; # same handler for all types, so we loop through them foreach my $type (qw(SCALAR ARRAY HASH)) { my $name = "UNIVERSAL::MODIFY_${type}_ATTRIBUTES"; my $old = \&$name; # Install our new attribute handler *$name = sub { my ($package,$ref,@attribute) = @_; _share( $ref ) if grep m#^shared$#, @attribute; # handle other attributes, is this needed? if (@attribute = grep !m#^shared$#,@attribute) { @attribute = $old->( $package,$ref,@attribute ); } return @attribute; } #$name } } #BEGIN
Now, what I'm wondering about is whether I should capture the code reference of the "old" handler, and pass on the remaining attributes to it. Or whether that this is somehow handled automatically.
If it is not needed, I'd like to remove it of course. But if it is needed and people use other attribute handlers, than that may cause the other attribute handlers not to be called and thus break other modules.
If this is a piece of solid code, I was thinking of using this approach for other attributes and/or generalizing this into a module.
Finally, yes I know about Attribute::Handlers, but since I'm only interested in tieing the reference, it seems like overkill to me. Especially looking at the compactness of the code I've created now.
Liz
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: forks.pm finally supports : shared attribute, correctly?
by scrottie (Scribe) on Sep 28, 2003 at 12:47 UTC |