List Info

Thread: RE: state vars: init with handle?




RE: state vars: init with handle?
user name
2007-09-19 06:45:23


> 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?

I think you are opening the same handle twice, the 
second time will close the previously opened file.

I think you need:

    sub lister {
        state $fh;
        unless($fh) { open $fh, "<",
"file" or die $!; }

The following should also work

    sub lister;
        state $fh = do { require IO::File;
		IO::File->new("< file") or die $! }
    
Robin
------------------------------------------------------------
-------
This e-mail and any attachments may contain confidential
and/or
privileged material; it is for the intended addressee(s)
only.
If you are not a named addressee, you must not use, retain
or
disclose such information.

NPL Management Ltd cannot guarantee that the e-mail or any
attachments are free from viruses.

NPL Management Ltd. Registered in England and Wales. No:
2937881
Registered Office: Serco House, 16 Bartley Wood Business
Park,
                   Hook, Hampshire, United Kingdom  RG27
9UY
------------------------------------------------------------
-------

[1]

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