Just a quick note to document a funny error.

I tried to remove trailing empty strings from an array of strings with the following code.

pop @msgstr while !length($msgstr[-1]);

This didn't work. Can you guess why? Solution under the fold.

This is an infinite loop if @msgstr contains only empty strings.

Comment on How not to remove trailing empty strings from an array
Select or Download Code
Re: How not to remove trailing empty strings from an array
by Neighbour (Friar) on Apr 16, 2013 at 14:32 UTC
    Close, but subtly different (imho), it
    is an infinite loop if @msgstr becomes the empty list because then -1 returns undef, which causes length to return undef, which is false and gets negated.
    You could fix this by using pop @msgstr while !length($msgstr[-1]//0); instead (perl v5.10 and up)

      My actual fix was

      pop @msgstr while @msgstr && !length($msgstr[-1]);
      Nope, I suppose ambrus also wants to strip trailing ...
      ... undefs

      Cheers Rolf

      ( addicted to the Perl Programming Language)

Re: How not to remove trailing empty strings from an array
by LanX (Canon) on Apr 16, 2013 at 17:17 UTC
    the problem comes from ...

    ...stringification of undef to ""

    I thought

    "" eq $arr[-1]
    could solve this, but no chance.

    Cheers Rolf

    ( addicted to the Perl Programming Language)