Greetings.

While extending functionality of one of the CPAN modules I've run into something strange.

The code is:

foreach my $name (@$fields) { # ... my $namedisplay = $1 if($name =~ /AS\s+(\S+)/i); warn "namedisplay: $namedisplay"; # 1-st warn # that's the lines I added to the code: if ( !$namedisplay && exists($obj->{labels}->{$name}) && $obj->{labels}->{$name}) { $namedisplay = $obj->{labels}->{$name}; } warn "namedisplay: $namedisplay"; # 2-nd warn # ... }
I was amazed to see that on each iteration $namedisplay is being assigned the same value (the $obj->{labels}->{$fields->[0]} one).

After splitting the line where $namedisplay first occured into declaration and assignment parts everything became OK.

my $namedisplay; $namedisplay = $1 if($name =~ /AS\s+(\S+)/i);

But I still don't understand what was happening before fix. I understand that $namedisplay was declared regardles of regex match (I was even begining to think the entire declaration could be skipped if regex didn't match). But it somehow remained alive throghout all loop iterations (1-st warn showed the same value for the variable on all iterations exept first one).

Will wise monks bring some light to this problem?


In reply to will you explain what's going on? by maard

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.