String-Interpolate-Delayed

 view release on metacpan or  search on metacpan

lib/String/Interpolate/Delayed.pm  view on Meta::CPAN

use 5.008;
use strict;
use warnings;

package String::Interpolate::Delayed;

our $AUTHORITY = "cpan:TOBYINK";
our $VERSION   = "0.002";

our $WORKAROUND = 1;

use overload q[""] => "interpolated", fallback => 1;

use PadWalker ();
use PerlX::QuoteOperator ();
use String::Interpolate ();
use UNIVERSAL::ref;

sub import
{
	my $class = shift;
	my ($name) = @_;
	
	my $code = sub ($) {
		my $text = shift;
		bless \$text;
	};
	
	"PerlX::QuoteOperator"->new->import(
		$name || "delayed",
		{ -emulate => 'q', -with => $code },
		scalar caller,
	);
}

sub new
{
	my $class = shift;
	my ($text) = @_;
	
	bless \$text => $class;
}

sub uninterpolated
{
	my $self = shift;
	
	return $$self;
}

sub _clean
{
	my ($refs) = @_;
	+{ map {; substr($_, 1) => $refs->{$_} } keys %$refs };
}

sub interpolated
{
	my $self = shift;
	
	my $stri = "String::Interpolate"->new;
	
	if ($WORKAROUND) {
		# Workaround for bug in the ->pragma() accessor...
		$$stri->{pragmas} = 'import strict "vars";';
	}
	else {
		$$stri->pragma('import strict "vars";');
	}
	
	$stri->exec(
		_clean(PadWalker::peek_our 1),
		_clean(PadWalker::peek_my 1),
		grep(ref($_) eq 'HASH', @_),
	);
	return $stri->exec($$self);
}

sub ref
{
	return undef;
}

1 && __PACKAGE__
__END__

=head1 NAME

String::Interpolate::Delayed - delay string interpolation until you really want it

=head1 SYNOPSIS

   use strict;
   use warnings;
   use String::Interpolate::Delayed;
   
   my $str   = delayed "$role of the $thing";
   my $role  = "Lord";
   my $thing = [qw( Rings Flies Dance )]->[rand 3];
   
   print "$str\n";

 view all matches for this distribution
 view release on metacpan -  search on metacpan

( run in 0.381 second using v1.00-cache-2.02-grep-82fe00e-cpan-9e6bc14194b )