http://qs1969.pair.com?node_id=72464
Category: Miscellaneous
Author/Contact Info Jeff japhy Pinyan
Description: This code allows you to escape loops immediately when a condition is met. It is currently named "Ensure", but I know you can think of a better name.
Before I show the code, let me tell you a few of the other names people have suggested for this module:
  • GetTheHellOutOfLoop
  • PHPSUX0R
  • You::Are::Sux
  • BlockF::cker
  • Ensure
  • Exiter
  • Exeter
  • Terminator
Personally, my favorite is BlockF::cker, but that wouldn't go over very well with the masses now, would it?

So right now, it's called Ensure. Here's a sample use:

use Ensure;
use strict;

my ($x,$limit) = (0,100);

ensure { $x < $limit } using($x), looping {
  print "Enter P,Q,R: ";
  chomp(my $numbers = <STDIN>);
  my ($p,$q,$r) = split /,/, $numbers;
  
  $x += $p;
  $x *= $q;
  $x /= $r;
};

print "Finally stopped at $x.\n";
What this code has saved me from doing is:
while ($x < $limit) {
  print "Enter P,Q,R: ";
  chomp(my $numbers = <STDIN>);
  my ($p,$q,$r) = split /,/, $numbers;
  
  $x += $p;
  last if $x >= $limit;
  $x *= $q;
  last if $x >= $limit;
  $x /= $r;
}
The point is that the module tracks accesses and modifications to a given list of variables, and will execute a conditional expression at each point. As soon as the condition is false, it stops the loop.

This is synonymous to walking around the block several times, and AS SOON as you see merlyn, you let me know. You don't wait to finish your current circuit, you tell me immediately.

Update: Here are some sample uses of the using() function:

ensure { ... } using($x,$y,$z), looping { ... };

ensure { ... } using($x,\@y), looping { ... };

ensure { ... } using($x,\%y,\@z), looping { ... };
Basically, scalars can be sent as-is. Arrays and hashes must be passed by reference. That's just the way it is. So here's the bloody code.
package Ensure;


use strict;
require Exporter;

@Ensure::ISA = qw( Exporter );
@Ensure::EXPORT = qw( ensure using looping );


sub ensure (&@) {
  my ($cref, $obj, $loop) = @_;
  for (@$obj) {
    if (not ref $$_) { tied($$_)->[1] = $cref }
    elsif (ref $$_ eq 'SCALAR') { tied($$$_)->[1] = $cref }
    elsif (ref $$_ eq 'ARRAY') { tied(@$$_)->[1] = $cref }
    else { tied(%$$_)->[1] = $cref }
  }
  eval { { $loop->(); redo } };
  die $@ if $@ ne "[Ensure]\n";
  untie $$_ for @$obj;
}


sub using (@) {
  my @obj;
  for (@_) {
    if (not ref) { tie $_, 'Ensure::Scalar' => $_ }
    elsif (ref eq 'SCALAR') { tie $$_, 'Ensure::Scalar' => $$_ }
    elsif (ref eq 'ARRAY') { tie @$_, 'Ensure::Array' => @$_ }
    elsif (ref eq 'HASH') { tie %$_, 'Ensure::Hash' => %$_ }
    else { next }
    push @obj, \$_;
  }
  return \@obj;
}


sub looping (&) { $_[0] }


package Ensure::Scalar;

sub TIESCALAR {
  my ($class, $val) = @_;
  bless [ $val ], $class;
}

sub FETCH {
  my $self = shift;
  my $val = $self->[0];
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub STORE {
  my ($self, $val) = @_;
  $self->[0] = $val;
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}


package Ensure::Array;

sub TIEARRAY {
  my $class = shift;
  bless [ [ @_ ] ], $class;
}

sub FETCH {
  my ($self, $i) = @_;
  my $val = $self->[0][$i];
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub FETCHSIZE {
  my $self = shift;
  my $size = @{ $self->[0] };
  die "[Ensure]\n" unless $self->[1]->();
  return $size;
}

sub STORE {
  my ($self, $i, $val) = @_;
  $self->[0][$i] = $val;
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub STORESIZE {
  my ($self, $size) = @_;
  $#{ $self->[0] } = $size;
  die "[Ensure]\n" unless $self->[1]->();
  return $size;
}

sub EXISTS {
  my ($self, $i) = @_;
  my $val = exists $self->[0][$i];
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub DELETE {
  my ($self, $i) = @_;
  my $val = delete $self->[0][$i];
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub PUSH {
  my $self = shift;
  for (@_) {
    push @{ $self->[0] }, $_;
    die "[Ensure]\n" unless $self->[1]->();
  }
  return scalar @{ $self->[0] };
}

sub POP {
  my $self = shift;
  my $val = pop @{ $self->[0] };
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub UNSHIFT {
  my $self = shift;
  for (reverse @_) {
    unshift @{ $self->[0] }, $_;
    die "[Ensure]\n" unless $self->[1]->();
  }
  return scalar @{ $self->[0] };
}

sub SHIFT {
  my $self = shift;
  my $val = shift @{ $self->[0] };
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub CLEAR {
  my $self = shift;  
  $self->[0] = [];
  die "[Ensure]\n" unless $self->[1]->();
  return;
}


package Ensure::Hash;

sub TIEHASH {
  my $class = shift;
  bless [ { @_ } ], $class;
}

sub FETCH {
  my ($self, $key) = @_;
  my $val = $self->[0]{$key};
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub STORE {
  my ($self, $key, $val) = @_;
  $self->[0]{$key} = $val;
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub FIRSTKEY {
  my $self = shift;
  my ($k,$v) = each %{ $_[0][0] };
  die "[Ensure]\n" unless $self->[1]->();
  return wantarray ? ($k,$v) : $k;
}

sub NEXTKEY {
  my $self = shift;
  my ($k,$v) = each %{ $_[0][0] };
  die "[Ensure]\n" unless $self->[1]->();
  return wantarray ? ($k,$v) : $k;
}

sub EXISTS {
  my ($self,$key) = @_;
  my $val = exists $self->[0]{$key};
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub DELETE {
  my ($self, $key) = @_;
  my $val = delete $self->[0]{$key};
  die "[Ensure]\n" unless $self->[1]->();
  return $val;
}

sub CLEAR {
  my $self = shift;  
  $self->[0] = {};
  die "[Ensure]\n" unless $self->[1]->();
  return;
}


1;
Replies are listed 'Best First'.
Re: Help Name This Module
by Corion (Patriarch) on Apr 14, 2001 at 01:36 UTC

    I like this module, and Ensure is an appropriate name IMO, but Loop::Invariant describes more clearly what the programmer intends to happen. Contract is a close third, while I find Assert unexpected in the sense that the program dosen't die when an assertion fails.

    But I have some problems with running your module :

    1. It dosen't run under Perl 5.5.3 (ActiveState Perl build 517)
    2. Under Perl 5.6.0 (IndigoPerl), I get Can't use string ("") as a subroutine ref while "strict refs" in use at Ensure.pm line 56. as an error in the Ensure::Scalar::FETCH sub. I think this comes from a conflict in execution order as follows :
      1. Ensure::using is called to tie the scalar, and sets up the Ensure::Scalar::FETCH handler.
      2. Ensure::ensure is called, and itself calls tied($$_), which in turn results in Ensure::Scalar::FETCH being called.
      3. Ensure::Scalar::FETCH is called and runs into the undef, as the handlers have not yet been set up (from within Ensure::ensure).

    The quick fix to me was a small change to the Ensure::Scalar module as follows :

    sub TIESCALAR { my ($class, $val) = @_; my $ref = [ $val, "setup", "setup" ]; bless $ref, $class; return $ref; } sub FETCH { my $self = shift; my $val = $self->[0]; if (ref($self->[1]) eq 'CODE') { die "[Ensure]\n" unless $self->[1]->(); }; return $val; }
    This fix would have to be repeated for the other modules (or maybe isn't necessary at all with Perl 5.6.1), and I'm not sure if my fix is really a fix and dosen't introduce more errors, as this is the first time I've dabbled with tie :-)

Re: Help Name This Module
by Masem (Monsignor) on Apr 14, 2001 at 00:22 UTC
    How about Short::Circuit, or possibly Data::Fuse, as what you've got suggests several parallels with electrical circuits.

    Alternatively, you could go with something like Execption::Watch or Data::Watch as that seems to be another thing this code pretty much does (a variant of exception handling).

    Excellent idea to write this, btw.


    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
Re: Help Name This Module
by knobunc (Pilgrim) on Apr 14, 2001 at 00:47 UTC

    How about somthing with Watch in it. This is kinda like the watch functionality of a debugger.

    Wandering CPAN a bit lead me to the Hook::PrePostCall which allows you to put an action before and after a subroutine call. The other subroutines in the Control Flow Utilities section are not in a sub package so they just have the base name. So maybe:

    • Hook::DataWatcher
    • Data::WatchVariable
    • Loop::Watch

    Very cool module. Any idea of the performance hit?

    -ben

(crazyinsomniac) Re: Help Name This Module
by crazyinsomniac (Prior) on Apr 14, 2001 at 04:57 UTC
    SquareLoop LoopBreak Loopy Loopor Lo'P the MotherLoopConnection(), as opposed to new MotherLoopConnection() Loopanismo LoopOperator StrictLoop LoopTorque LoopRollerCoaster Poop LoopVader or LoopInvader LoopSadist LoopNazi LoopyPop LoopBastard LoopBonK LoopOnCrank LoopDeDo

     
    ___crazyinsomniac_______________________________________
    Disclaimer: Don't blame. It came from inside the void

    perl -e "$q=$_;map({chr unpack qq;H*;,$_}split(q;;,q*H*));print;$q/$q;"

(jcwren) Re: Help Name This Module
by jcwren (Prior) on Apr 14, 2001 at 01:18 UTC

    Tie::VarLimit

    --Chris

    e-mail jcwren
(redmist) Re: Help Name This Module
by redmist (Deacon) on Apr 14, 2001 at 05:35 UTC

    I really like Masem's Short::Curcuit idea. How about Loop::AWOL?

    redmist
    Silicon Cowboy
Re: Help Name This Module
by ZZamboni (Curate) on Apr 14, 2001 at 07:47 UTC
    Very cool module! Clear demonstration of the very powerful things you can do with Perl. I would vote for Data::Watch or Loop::Watch.

    --ZZamboni

Re: Help Name This Module
by japhy (Canon) on Apr 14, 2001 at 02:18 UTC