Having just read merlyn's Alpaca book, and thus being in "Object Oriented" mode when I read Ovid's question, I started thinking of an OOP alternative to using $`, $', and $&.
In this solution I tie three scalars to behave just like the infamous special variables, but without the global performance hit. Unfortunately, the string being matched against must be passed by reference to the objects as the scalars are being tied. For that reason, this solution feels a little kludgy to me, but I thought it was interesting enough to post anyway.
I haven't made any attempt to guard against undefined @- and @+ in the case of unsuccessful matches, and it may go to hell in a handbasket for s/// where the string changes length. But it's still kinda fun to play with. Enjoy!
Dave
package Match; use strict; use warnings; sub TIESCALAR { my ( $class, $r_string ) = @_; my $self = {}; $self->{String_Ref} = $r_string; $self->{Value} = undef; bless $self, $class; } sub STORE { my ( $self, $value ) = @_; $self->{Value} = $value; return $self->{Value}; } sub FETCH { my $self = shift; $self->{Value} = substr( ${$self->{String_Ref}}, $-[0], $+[0] - $-[0] ); return $self->{Value}; } sub DESTROY { my $self = shift; } 1; package Prematch; use base "Match"; sub FETCH { my $self = shift; $self->{Value} = substr( ${$self->{String_Ref}}, 0, $-[0] ); return $self->{Value}; } 1; package Postmatch; use base "Match"; sub FETCH { my $self = shift; $self->{Value} = substr( ${$self->{String_Ref}}, $+[0] ); return $self->{Value}; } 1; # ---------- Begin main ---------- package main; use strict; use warnings; my ( $match, $pre, $post ); my $string = "This is a contrived test string..."; tie $match, "Match", \$string; tie $pre, "Prematch", \$string; tie $post, "Postmatch", \$string; if ( $string =~ /contrived/) { print $pre,"\n"; print $match, "\n"; print $post, "\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Tied scalars to emulate $&, $' and $` without global performance hit
by Anonymous Monk on Dec 21, 2003 at 17:35 UTC | |
|
Re: Tied scalars to emulate $&, $' and $` without global performance hit
by davido (Cardinal) on Dec 22, 2003 at 03:32 UTC |