in reply to regex transforms of object attributes

If modifying the content is something you often do, it would be kind of cool to have the set method take a block of code and act internally:
$self->content(sub{s/foo/bar/g});
where the content method would recognize the code ref and treat the current value as $_ within it. Something vaguely like:
sub content { my $self = shift; if (@_) { my $set = shift; if (isa($set,"CODE")) { # fixed :-) &$set for $self->{'content'}; # Code to modify content (as + $_) gets executed } else { $self->{'content'} = $set; # Direct set } } $self->{'content'}; }
Another spiffy (but experimental) technique would be to make the content method an lvalue subroutine. So you could write the one-liner
$self->content =~ s/foo/bar/g; # instead of # $self->content(map { s/foo/bar/g } map $_, $self->content);

We're not really tightening our belts, it just feels that way because we're getting fatter.

Replies are listed 'Best First'.
Re^2: regex transforms of object attributes
by belden (Friar) on Jun 18, 2004 at 23:50 UTC

    You've got a bug:

    if (isa($set,"CODE")) { &set for $self->{'content'}; # Code to modify content }

    That tries to call the subroutine set(). What you mean is:

    if (isa($set,"CODE")) { $set->() for $self->{'content'} # execute the $set coderef }