stm has asked for the wisdom of the Perl Monks concerning the following question:


Hello,

This question is related to Tie::File module. Have opened a file and processing array functions. Then processing do while loop, here the script has to exit if conditions are met.

Is it OK to use exit to exit the script without untie the file handle ? or any better solution available? last statement is not working here. It says an error "Can't "last" outside a loop block at". Copied few lines of my code to keep simple.

tie my @in_array, 'Tie::File', $fileA, mode => O_RDWR or die $!; my $f_cnt = scalar(@in_array); my $retries; do { ##have removed lines for simplicity ## $retries++; if ($retries > 3) { print "3 attempts are failed.\n"; exit(); } } while ($f_cnt > 1 ); untie @in_array;

Replies are listed 'Best First'.
Re: Tie::File: untie file handle
by Athanasius (Archbishop) on Aug 03, 2015 at 13:22 UTC

    Hello stm,

    last statement is not working here. It says an error "Can't "last" outside a loop block at".

    That’s because the do { ... } while (...); construct isn’t a “real” loop; it’s a do operator followed by a while modifier. See perlsyn#Statement-Modifiers. You can re-cast your loop as follows:

    { do { ... if ($retries > 3) { print "3 attempts are failed.\n"; last; } } while ($f_cnt > 1); }

    Update 1: Originally I had a LOOP: label on the outer block, and last LOOP; inside the if block; but a simple last; works just as well, and the label isn’t needed.

    Alternatively, you could just add another untie @in_array statement immediately before the call to exit.

    Update 2: Yet another option is to put the untie statement in an END { ... } block. The contents of any END block(s) will be executed when the script terminates, even if the termination is produced by a call to exit or die.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Tie::File, is untie file handle must?
by u65 (Chaplain) on Aug 04, 2015 at 13:29 UTC

    And a nit pick: the bare

    my $retries;

    bothers me. I prefer always setting the initial state of such variables:

    my $retries = 0;

      Curious about this. Why?

      The way forward always starts with a minimal test.

        Because its value is undefined.

        Update: And I don't that's good practice when we're going to change its value with an increment operation in a following loop.