I've been trying to wrap my head around map. I think I was going about it all wrong, trying examples and such just to see how it worked. It was probably to complicated for me, so I gave up and tried to play with grep for a while. It was a lot easier to understand. So now back with map, I've got a function that calculates a running total. My first thought was

map {$n[$#n+1]=($count+=$_)} <DATA>;

but then I realized that map was returning a list anyway, so I probably didn't need @n at all. I came up with

@n=map {$count+=$_} <DATA>;

Is this a good way to do it?

Also, I was wondering if you could do it with grep? I don't know why you'd want to, but it seems to me like you should be able to.

@n=map {$count+=$_} <DATA>; print "@n\n"; __DATA__ 1 2 3 6 -5 6
outputs this
1 3 6 12 7 13
which is what I was aiming for.

In reply to playing with map by coolmichael

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.