Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

length of string in array

by SavannahLion (Pilgrim)
on Feb 28, 2017 at 21:16 UTC ( [id://1183197]=perlquestion: print w/replies, xml ) Need Help??

SavannahLion has asked for the wisdom of the Perl Monks concerning the following question:

After three days of trying to track down an annoying bug, I finally traced it to this innocuous line, I stripped all the cruft out:

my @t = qw/aA bB cC dD eE fF gG hH iI jJ kK lL mMmM nN oO pP qQ rR sS +tT uU vV wW xX yY Zz/; my $x = 0; $x = length for @t[0 .. 1]; print $x;

What the code is supposed to do is print out "4". Instead it prints out "2". Clearly there is something amiss here.

What I thought the code does is get a slice of @t, loop through the sliced elements in @t, get the length of each one and assign the sum to $x.

I've tweaked this portion of my code for three days and I can't seem to get it behaving right. Ironically, I've actually gotten similar (albeit more convoluted code) actually working in different language. So there is clearly some nuance I'm missing here.

Replies are listed 'Best First'.
Re: length of string in array
by 1nickt (Canon) on Feb 28, 2017 at 21:27 UTC

    Hi SavannahLion,

    You are reassigning to $x each time through the loop. Add to it instead:

    $x += length for @t[0..1];

    Hope this helps!


    The way forward always starts with a minimal test.

      Aaagghh! I was so focused on trying to figure out why length for @t[0 .. 1] wasn't working as it should that I completely overlooked the assignment!
      So much time wasted!

      Sigh... many thanks

Re: length of string in array
by AnomalousMonk (Archbishop) on Feb 28, 2017 at 21:52 UTC

    And if you actually want to use a (completely supererogatory) List::Util::sum() function:

    c:\@Work\Perl\monks>perl -wMstrict -le "use List::Util qw(sum); ;; my @t = qw/aA bB cC dD eE fF/; my $x = sum map length, @t[0 .. 1]; print $x; " 4


    Give a man a fish:  <%-{-{-{-<

Re: length of string in array
by GotToBTru (Prior) on Feb 28, 2017 at 21:28 UTC

    I don't see any summing going on. Perhaps:

    $x += length for @t[0..1];
    But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1183197]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-19 00:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found