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

In my below code snippet ,the array @header_present is always true,the value pushed into it gets stuck here,I am clearing the data at the start of the loop again but still the array condition some how is always true.Can some one advise what is wrong?

my @headers; my @header_present=" "; #clearing the data here if ($line =~ /.\data/) { push @header_present,grep( (/\Q$line\E/i), @headers); if(@header_present)#this is always true,the value pushed + above gets stuck,how to clear the array when it executes next time? { }

Replies are listed 'Best First'.
Re: Array condition always true
by moritz (Cardinal) on Mar 20, 2011 at 09:42 UTC
    my @header_present=" "; #clearing the data here

    This places one element into @header_present, which is a string consisting of a single space. Arrays are true if they contain at least one item, that's the case after this piece of code.

    The right thing would be not to assign anything; my @var automatically creates a new, fresh, empty array.

    If you want to clear an array later on, you can write

    # recommended: @var = (); # or a bit more excotic: $#var = -1;

    You can read more about that in perldata.

    You would do well to adapt a consistent code indenting style. See perlstyle for example.

      How to free it its a scalar variable instead of an array meaning if @header_present is $header_present

      Will $header_present=" "; work?

        What do you want to achieve? $header_present = ''; will set $header_present to an empty string. $header_present = undef; will set $header_present to undef which is the uninitialised state. The one you need depends on code you've not shown us.

        True laziness is hard work
Re: Array condition always true
by GrandFather (Saint) on Mar 20, 2011 at 09:11 UTC

    What next time? The code as shown only executes once. The block controlled by if(@header_present) will execute if anything were pushed into @header_present in the previous line and that will never happen with the code shown because @headers is empty.

    In this question and a previous question you posted it seems there is a larger context that we are not being shown that is strongly related to the problems you are having. For us to be able to help you need to isolate the problems into a small run-able script that shows the issue you need to fix and show that to us. Describing the larger context will probably help too. See I know what I mean. Why don't you? for ideas on how to create such a script.

    True laziness is hard work

      Sorry abt the confusion.I figured out the prob:-)