develooper Front page | perl.perl6.language | Postings from February 2005

Closure trait for loop entry

Thread Next
From:
Joe Gottman
Date:
February 12, 2005 07:22
Subject:
Closure trait for loop entry
Message ID:
200502121522.j1CFMDee024479@ms-smtp-02-eri0.southeast.rr.com
   Often when I write a loop I want to run some code at loop entry time.  It
would be nice to have a closure trait for this, similar to NEXT for loop
continuation or LAST for loop termination, but there isn't one.  I don't
think either FIRST or ENTER do quite what I want.  FIRST runs only once,
which is too few times, and ENTER runs every time the loop block is entered,
which is too many.

   To demonstrate what I want, consider the following examples:

   sub use_first() 
   {
	for 1..2 {
		FIRST {say 'entering loop';}
		say $_; 
		LAST	{say 'leaving loop';}
	}
  }

  sub use_enter()  
   {
	for 1..2 {
		ENTER {say 'entering loop';}
		say $_; 
		LAST	{say 'leaving loop';}
	}
  }


The first time use_first is called it will print
	entering loop
	1
	2
	leaving loop

but subsequently it will print
	1
	2
	leaving loop

and leave out the 'entering loop'.

When use_enter is called it will print
	entering loop
	1
	entering loop
	2
	leaving loop

I want to output
	entering loop
	1
	2
	leaving loop

every time I run my loop. I suggest we create a new closure trait called
SETUP for this.  Then the code could read

	for 1..2 {
		SETUP {say 'entering loop';}
		say $_; 
		LAST	{say 'leaving loop';}
	}

Since SETUP can be used for initialization, it should probably be allowed
within an expression:
	state $first_iteration = SETUP {true} will next {$_ = false};

Lower case 'setup' could probably also be used as a trait on a variable
	state $first_iteration will setup {$_ = true} will next {$_ =
false};

Joe Gottman



Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About