develooper Front page | perl.perl5.porters | Postings from March 2013

Re: Infinite loop in for (@a) { push @a, $_ }

Thread Previous | Thread Next
From:
Brad Gilbert
Date:
March 19, 2013 16:56
Subject:
Re: Infinite loop in for (@a) { push @a, $_ }
Message ID:
CAD2L-T1jed_gr18r+PPK6MJAN96sR3_qXO8g0aQhfdDxnye1rg@mail.gmail.com
On Tue, Mar 19, 2013 at 11:10 AM, Zefram <zefram@fysh.org> wrote:
> Brad Gilbert wrote:
>>$ perl -E'@a=10;for(@a){push @a, $_-1 if $_} say join ",", @a'
>
> That falls squarely within the range of things that perlsyn(1) warns
> you not to do.  We can break that with a clear conscience, if we have
> a better behaviour to implement.
>
> The only behaviour that I think it would be worth changing this for
> is to detect modification of an array being iterated over and to die
> when that happens.  (Either immediately upon modification or at the
> start of the next iteration after modification.)  This could perhaps be
> achieved, with acceptable performance characteristics, by something akin
> to local()ly setting the readonly flag on the array while it's being
> used by the iterator.  (Best not the actual SvREADONLY flag, as that
> implies that the array will *always* be read-only.  But we're short of
> spare flag bits.)
>
> -zefram

I think I would be fine with that, as long as it's optional.

I assume it would only warn/die if the length of the array can
change.

    @a = map{ $_, undef } 0..10; # just an example set of data

    for( @a ){
      $_ //= 0; # should still work
    }

    say join ',', @a;

Though this is really only a problem when the length of the
array can get bigger.

    my $s = join '', 'a'..'f';
    $s .= reverse $s;

    if( is_palindrome($s) ){
      say qq['$s' is a palindrome];
    }

    sub is_palindrome {
      my ($s) = @_;
      my @s = split //, $s;

      for( @s ){
        if( $_ ne pop @s ){
          return;
        }
      }
      return 1;
    }

Thread Previous | 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