Syntactic Confectionery Delight PerlMonks

### Comment on

 Need Help??

"23 s stored as a single byte hence i cant split."

Byte?! You're thinking in C terms! Go wash your mouth out with soap right now! ;-)

In Perl, strings and integers are both represented by the same data type - scalars. (Internally Perl represents scalars as a C struct which has separate string and integer slots. But you don't normally need to worry about such concerns.) If you have a variable that contains an integer value, such as 23, and pass it to something that expects a string, like split, that integer will be silently converted to a string.

Here's exactly the same function I posted before, only now I'm using the integer 23 as the input...

```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

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);
}
perl -E'sub Monkey::do{say\$_,for@_,do{(\$monkey=[caller(0)]->[3])=~s{::}{ }and\$monkey}}"Monkey say"->Monkey::do'

In reply to Re^5: How to split an integer?? by tobyink
in thread How to split an integer?? by nithins

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.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, 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, 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: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2018-03-20 02:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When I think of a mole I think of:

Results (247 votes). Check out past polls.

Notices?