use 5.010; use strict; use warnings; # 23 is an integer. # say digit_sum(23); # This expression is used to test that a string consists of a single # digit. We use it a couple of different places, so we'll get define # it once here. # use constant DIGIT => qr/^[0-9]$/; # This is the function which adds digits # sub digit_sum { my $string = shift; # Otherwise, split into digits. my @digits = grep { $_ =~ DIGIT } # keep only the numeric characters split '', $string; # split into characters # Add the digits together. my $sum = 0; $sum += $_ for @digits; # Handle the trivial case. # If $sum is just a single digit, return it as-is. return $sum if $sum =~ DIGIT; # Otherwise, recurse. return digit_sum($sum); }