Hi monks,
I'm trying to understand the behavior of the given-when construct
when I use an array reference in the "when" clause.
I saw a similar example in "Programming Perl - 4th ed."
but it's not doing what I expected.
I have this test case:
#!/usr/bin/env perl
use v5.14;
my @array = (0, 1000..10_000, 'abcd');
for my $element (qw/a ab abc 100 1000 10000 abcd/) {
say "With grep:";
if (grep {/^$element$/} @array) {
say "Element $element is there";
} else {
say "Element $element is not there";
}
say "With given-when:";
given ($element) {
when (\@array) {
say "Element $element is there";
}
default {
say "Element $element is not there";
}
}
say "";
}
It yields this result:
With grep:
Element a is not there
With given-when:
Element a is there
With grep:
Element ab is not there
With given-when:
Element ab is there
With grep:
Element abc is not there
With given-when:
Element abc is there
With grep:
Element 100 is not there
With given-when:
Element 100 is not there
With grep:
Element 1000 is there
With given-when:
Element 1000 is there
With grep:
Element 10000 is there
With given-when:
Element 10000 is there
With grep:
Element abcd is there
With given-when:
Element abcd is there
The 'grep' gets it right every time.
The given-when construct finds elements 'a', 'ab' and 'abc' even if the're not in @array.
The funny thing is: if I remove the
0 from @array,
elements 'a', 'ab' and 'abc' are reported as "not there",
so the matching element seems to be the 0.
I'm rather puzzled.
Can someone explain this?
Thanks,
bye.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.