Sum of Numbers in an Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nathan Belomy
    New Member
    • Sep 2011
    • 4

    Sum of Numbers in an Array

    Code:
    #!/usr/bin/perl
    
    @array = (1..1000);
    
    sub total {
    my($v1) = print @array;
    } 
    
    my($output) = &total();
    I'll figure it out. Don't need your help. Thanks. Since the array is just

    @array = (1..1000);
    print @array;

    or

    some bs, this thing sucks.
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    Just because I was in a coding mood:

    Code:
    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my @array = (1..10);
    my $sum = 0;
    
    foreach my $num (@array){
    	$sum = $sum + $num;
    }
    
    print("The sum is:  $sum\n");
    Please notice the pragmas at the beginning, "use strict;" and "use warnings;". You want to use those at the beginning of every Perl script you write. They will save you a ton of headache.

    Regards,

    Jeff

    Comment

    • Nathan Belomy
      New Member
      • Sep 2011
      • 4

      #3
      That helps a bunch. Man I still got a lot to learn. That little trick
      $1 = $1 + $other didn't know you could do that. Yah man thanks again since I actually got so pissed, I broke something. At least I don't own a gun.

      Comment

      • Nathan Belomy
        New Member
        • Sep 2011
        • 4

        #4
        Code:
        #!/usr/bin/perl
        
        use strict;
        use warnings;
        
        my @array = (1..1000);
        my $sum = 0;
        
        foreach my $num (@array){
            $sum = $sum + $num;
        }
        
        sub total {
        my($v1) = print $sum;
        }
        
        
        my($output) = &total();
        print "$output\n";
        Happy as a clown. Only thing is, I'm right when I say the foreach is not a subroutine, it's a loop. Yah so this is correct.

        Comment

        • chorny
          Recognized Expert New Member
          • Jan 2008
          • 80

          #5
          Code:
          use List::Util 'sum';
          $sum=sum(@array);

          Comment

          • Nathan Belomy
            New Member
            • Sep 2011
            • 4

            #6
            Thank You, I will try one too. So kind of you both to help me. Really appreciate that.

            Comment

            Working...