List Info

Thread: state vars: init with handle?




state vars: init with handle?
user name
2007-09-19 06:35:08
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?


Re: state vars: init with handle?
user name
2007-09-19 06:39: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 $!;

[1-2]

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