perl - Why does this map return a single number? -


I am trying to cut the number of code lines which I am using, but a fairly simple problem (though This is stumping me because I'm just starting to wrap my head around references)

I want to add many values ​​in a particular order. My code looks like this ..

  my $ separator = ":"; My @vals = qw (name last name first name phone); My $ return_name; $ Return_name = Map {$ return_name = $ return_name $ Query- & gt; Ultimate ($ _ $ $ separator) @el;  

What I'm getting "4", instead of writing all in one string

What I'm trying to achieve is a small version of ...

  $ return_name = $ query- & gt; The ultimate ('name'). $ Separator $ query- & gt; Ultimate ('lastname') $ separator $ Query- & gt; Ultimate ('first_name'). $ Separator $ Query-> Ultimate ('Phone');  

(I'm actually trying to string about 25 simultaneously $ query-> params . I only gave four for short) < / P>

One part of your problem is confusion as to how the map works .

Map takes a list of arguments, performs an operation on the elements of the list and creates a new list from the result. In scalar context, it gives the number of members in the new list.

In most cases you do not want to do an assignment in the map operation.

  # @foo = Map $ _ + 2, 1,2,3; #foo = (3,4,5);  

At one place where the assignment is understood, if you have to use an operation which will usually change the value of $ _ , Will need to be preserved to mapped unchanged.

This explanation is not very clear, look at these examples, they should explain what I am saying. The first map can change the prices shown to you:

  my @foo = qw (fee fee enemy fum); My @ bar = map {s / e / - / g} @fu; #fu = ('F-', 'fi', 'fay-', 'foam'); # @bar = (2, 1, 1, '');  

To avoid changing the lungs, you can:

  my @foo = qw (feefu futures); My @ bar = map {my $ val = $ _; $ Val = ~ s / e / - / g} @foo; #fu = ('fee', 'fi', 'enemy', 'fm'); # @bar = ('F-', 'fi', 'fo-', 'fm');  

Or you can:

list :: MoreUtils qw (applicable);

  my @foo = qw (fee fee enemy fum); My @ bar = apply {s / e / - / g} @foo; #fu = ('fee', 'fi', 'enemy', 'fm'); # @bar = ('F-', 'fi', 'fo-', 'fm');   

The map on works specifically for the loop, two parts of the code produce exact same results:

  my @foo = map {$ _ * 2} 1..5; My @ bar; (1..5) {my $ val = $ _ * 2; Push @ bar, $ well; }  

I hope that you have given some help in learning to think about map . Once you have learned to use it (and related constructions such as grep and apply ), you will be able to express simple ideas, which are common Using the looping code can be incredibly executed. / P>


Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -