package Variable::Temp;

use 5.006;

use strict;
use warnings;

=head1 NAME

Variable::Temp - Temporarily change the value of a variable.

=head1 VERSION

Version 0.01

=cut

our $VERSION;
BEGIN {
 $VERSION = '0.01';
}

=head1 SYNOPSIS

    use Variable::Temp 'temp';

    my $x = 1;
    say $x; # 1
    {
     temp $x = 2;
     say $x; # 2
    }
    say $x; # 1

=head1 DESCRIPTION

This module provides an utility routine that can be used to temporarily change the value of a variable, until the end of the current scope is reached where the original value of the variable is restored.
It is similar to C<local>, except that it can be applied onto lexicals as well as globals, and that it replaces values by copying the new value into the container variable instead of by aliasing.

=cut

use Scope::Upper;

=head1 FUNCTIONS

=head2 C<temp>

    temp $var;
    temp $var = $value;

Temporarily replace the value of the lexical or global variable C<$var> by C<$value>, or by C<undef> if C<$value> is omitted, until the end of the current scope.
Any subsequent assignments to C<$var> in the current (or any inferior) scope will not affect the original value which will be restored into the variable at scope end.
Several C<temp> calls can be made onto the same variable, and the restore are processed in reverse order.

Note that destructors associated with C<$var> will B<not> be called when C<temp> sets the temporary value, but only at the natural end of life of the variable (i.e. at the end of the scope).
They will trigger after any destructor associated with the replacement C<$value>.

=cut

sub temp (\$) :lvalue {
 my $var  = $_[0];
 my $save = $$var;
 &Scope::Upper::reap(sub { $$var = $save } => Scope::Upper::UP);
 $$var;
}

=head1 EXPORT

The function L</temp> is only exported on request by passing C<'temp'> to the module import list.

=cut

use base 'Exporter';

our @EXPORT      = ();
our %EXPORT_TAGS = ();
our @EXPORT_OK   = 'temp';

=head1 CAVEATS

Currently only applies to scalar variables.

=head1 DEPENDENCIES

L<perl> 5.6.

L<Scope::Upper>.

L<Exporter> (core since perl 5).

=head1 SEE ALSO

L<Scope::Upper>.

L<perlfunc/local>.

=head1 AUTHOR

Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.

You can contact me by mail or on C<irc.perl.org> (vincent).

=head1 BUGS

Please report any bugs or feature requests to C<bug-variable-temp at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Variable-Temp>.
I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Variable::Temp

=head1 COPYRIGHT & LICENSE

Copyright 2015 Vincent Pit, all rights reserved.

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.

=cut

1; # End of Variable::Temp
