package MatchVars; use vars qw($string $match $prematch $postmatch $_internal $_init); $_internal = ""; $_init = 0; sub string { shift if ref($_[0]) eq "MatchVars" || (@_ > 1 && $_[0] eq "MatchVars"); return $_internal unless @_; $_internal = \ $_[0] } sub import { no strict; my $caller = caller(); unless ($_init) { tie $string, "MatchVars::string", \$_internal; tie $match, "MatchVars::Match", \$_internal; tie $prematch, "MatchVars::Prematch", \$_internal; tie $postmatch, "MatchVars::Postmatch", \$_internal; $_init = 1; } *{"$caller\::_string"} = \$string; *{"$caller\::_match"} = \$match; *{"$caller\::_prematch"} = \$prematch; *{"$caller\::_postmatch"} = \$postmatch; } package MatchVars::string; sub TIESCALAR { my ( $class, $r_string ) = @_; bless \do{my $o = $r_string},$class; } sub STORE { my $self = shift; $$$self = \ $_[0]; } sub FETCH { my $self = shift; return $$$$self; } sub UNTIE { } sub DESTROY { } package MatchVars::base; sub TIESCALAR { my ( $class, $r_string ) = @_; bless \do{my $o = $r_string},$class; } sub STORE { } sub UNTIE { } sub DESTROY { } package MatchVars::Match; use base "MatchVars::base"; sub FETCH { my $self = shift; no warnings; my $return = substr($$$$self, $-[0], $+[0] - $-[0] ); return defined $return?$return:""; } package MatchVars::Prematch; use base "MatchVars::base"; sub FETCH { my $self = shift; no warnings; my $return = substr($$$$self,0, $-[0] ); return defined $return?$return:""; } package MatchVars::Postmatch; use base "MatchVars::base"; sub FETCH { my $self = shift; no warnings; my $return = substr($$$$self, $+[0]); return defined $return?$return:""; } 1; # END OF MatchVars.pm __END__ #!/usr/bin/perl -wl use strict; use MatchVars; # Let's try it out my $var1 = "pre=match=post"; $_string = $var1; print "1: $_prematch | $_match | $_postmatch" if $var1 =~ /=\w+=/; # 1: pre | =match= | post # But this doesn't work properly if you change $var my $var2 = "pre=match=post"; $_string = $var2; $var2 = "this=is_not=right"; print "2: $_prematch | $_match | $_postmatch" if $var2 =~ /=\w+=/; # 2: pre= | match=po | st # But this is a workaround my $var3 = "pre=match=post"; MatchVars->string($var3); $var3 = "this=shows=up"; print "3: $_prematch | $_match | $_postmatch" if $var3 =~ /=\w+=/; # this | =shows= | up