List Info

Thread: AW: state vars: init with handle?




AW: state vars: init with handle?
user name
2007-09-19 06:52:31
> On 19/09/2007, Dintelmann, Peter 
> <Peter.Dintelmanndresdner-bank.com>
wrote:
> > I want to use state vars for file iterators like
> > in
> >
> >     use strict;
> >     use feature qw(state);
> >
> >     sub lister {
> >         open state $fh, "<",
"file" or die $!;
> >         print scalar <$fh>;
> >         eof $fh and close $fh;
> >     }
> >
> >     lister(), lister();
> >
> > The open() call seems to be executed twice
contrary
> > to my expectations and the first line of
"file" is
> > printed twice instead of the first and second
line.
> >
> > Are my expectations wrong?
> 
> Yes. The only special one-time initialisation occurs
with the syntax
> C<state $x = "foo">. You'll need
something like the untested (but
> should work):
> 
> state $fh // open $fh, "<",
"file" or die $!;

	Global symbol "$fh" requires explicit package
name ...
	But in principle it works this way.
	Robins solution also does the right thing.

	Thanks for the hints.

      Since my original syntax looks so intuitive (at least
	to me , can I
have it as a feature request?


Re: state vars: init with handle?
user name
2007-09-19 07:31:53
On 19/09/2007, Dintelmann, Peter <Peter.Dintelmanndresdner-bank.com>
> > state $fh // open $fh, "<",
"file" or die $!;
>
>         Global symbol "$fh" requires explicit
package name ...

Ah, yes, of course.

>         But in principle it works this way.
>         Robins solution also does the right thing.
>
>         Thanks for the hints.
>
>       Since my original syntax looks so intuitive (at
least
>         to me , can I
have it as a feature request?

Well, given that open() is one of the very few built-ins
that modify
its argument (with sysopen() -- any others?), and that the
"open my"
idiom is common, I think that could be allowed as some more
example of
DWIMmery. Provided it also works when CORE::open is
overriden.

[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )