3

I am not able to understand why following code is not working.

<%method getvivekBox>
  <%args>
   $BoxName
  </%args>

  <%perl>
    return {
      type        => 'vivek',
    };
  </%perl>
</%method>




<%method getAll>
 <%args>
  $BoxGroup
  $indexex
 </%args>
  <%perl>
    my $x =  map { $m->comp('SELF:getvivekBox' , BoxName => "$BoxGroup-$_"); } @$indexex;

    return $x;
  </%perl>
</%method>

I am calling getAll with arguments , box and (1..10). It is returning 11 but expected behavior for me it should return 10 elements.

Vivek Goel
  • 22,942
  • 29
  • 114
  • 186

1 Answers1

3

map on a list produces another list. You are assigning the result of the map to a scalar, thus getting the number of elements assigned to $x.

Change $x to @x, or put [] around the map (to make $x an array reference).

asjo
  • 3,084
  • 2
  • 26
  • 20
  • 2
    Won't you be getting the number of elements in the list? – Sobrique Feb 11 '15 at 19:01
  • Nope, give it a try: perl -E '$x=(1,1,1,17); say $x' - prints 17. If you put parenthesis around the $x, you get the first element, by the way. – asjo Feb 11 '15 at 19:08
  • 2
    @asjo No it's definitely the count in this case. See `perl -e '@a=(4,5,6);$x=map {$_} @a; print "$x\n";'` – AKHolland Feb 11 '15 at 19:32
  • 3
    You're right that a list in scalar context evaluates to the last element in the list, but in this case, you're calling a function (`map`). Different functions return different things in scalar context, so you should consult the [documentation for `map`](http://perldoc.perl.org/functions/map.html): "In scalar context, returns the total number of elements so generated." Sobrique and AKHolland are correct. – ThisSuitIsBlackNot Feb 11 '15 at 20:01
  • 4
    @ThisSuitIsBlackNot: more correctly, the comma operator in scalar context gets you the last element in the list. – ysth Feb 11 '15 at 20:25
  • 1
    @ysth Thank you, I kind of felt like I was missing something (I thought it was magic). – ThisSuitIsBlackNot Feb 11 '15 at 20:45
  • Thanks for putting me straight, my test was too simple. D'oh. (It is confusing to me that map does something else than a list in scalar context, but that is no excuse.) – asjo Feb 11 '15 at 20:55
  • 1
    @asjo: lists don't ever get produced in scalar context; instead, every operator or builtin function does what seems like the most reasonable thing to do, and the documentation will tell you what that is. – ysth Feb 11 '15 at 23:16
  • @ysth Indeed. One of the warts of Perl 5 I don't hit that often, fortunately. – asjo Feb 12 '15 at 19:21