1

I am very new to perl and I am learning this is not like c++. So The user will enter a number of any length, and I want to add each digit and print the sum.

#!/usr/bin/perl -w
use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;

my @array = $num;
my $sum=0;
for my $arr (@array){

    $sum += $arr;

print $sum;
}

For example the user enters 1234, the sum: 10 the actual result I get is 1234.

pii_ke
  • 2,811
  • 2
  • 20
  • 30
Nameishi
  • 185
  • 1
  • 14

2 Answers2

4

You need to break the input string $num into separate digits. Try replacing my @array = $num with my @array = split //, $num. Read more by running perldoc -f split.

In Perl both strings and numbers are classified as SCALARs. A scalar is automatically treated as a number if arithmetic operations (like +) are done with them, so the summation inside the for loop works as expected.

zdim
  • 64,580
  • 5
  • 52
  • 81
pii_ke
  • 2,811
  • 2
  • 20
  • 30
  • It is also first checked whether it [looks_like_number](https://perldoc.perl.org/perlapi.html#looks_like_number) – zdim Dec 06 '17 at 06:12
2

You Just need to add two lines

use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;

#You missed out to remove the entermark at the end
chomp($num); my $newnum = "0";

$newnum += $_  for split//, $num;

print $newnum;

Note: I didn't override or not considering the method what you have followed however I just did what I know in perl.

Further More details

ssr1012
  • 2,573
  • 1
  • 18
  • 30
  • Obviously, I don't know how to explain this really in theoretically. Since I am also learner in perl just little bit having some idea while doing in practically. – ssr1012 Dec 06 '17 at 08:52
  • i'm kind of new to perl too, Is there a difference between the syntax `split //, $num` and `split('', $num)`? I was used to the second one but I now see the first one everywhere – Flying_whale Dec 06 '17 at 09:14
  • Don't use `map` when you mean `for`. – Borodin Dec 06 '17 at 09:15
  • @Borodin: This is for me then I couldn't understand the comment... Please just give in detail. – ssr1012 Dec 06 '17 at 10:00
  • `map` is for "mapping" one list to another. `map { $newnum += $_ } split //, $num` should be `$newnum += $_ for split //, $num`. – Borodin Dec 06 '17 at 10:04
  • @Borodin: Thanks I understood and updated the answer. – ssr1012 Dec 06 '17 at 10:17
  • 1
    @Flying_whale: the two calls to `split` are syntactically identical, you can omit the parentheses on perl's built-in functions (and your own on certain conditions). Adding them may be useful for clarity in longer expressionts though. – Jochen Lutz Dec 06 '17 at 10:58