You have warnings on! Why don't you read the warning you get?
Useless use of exponentiation (**) in void context means that your
$j**3 line isn't doing anything with its return value. Perhaps you meant
$j **= 3 which would set $j to itself cubed.
I assume you have a sum() function defined somewhere. And your variable scoping leaves something to be desired -- specifically, proper variable scoping. Rewriting only the scoping of your program, I'd do:
my @numbers;
for my $i (100 .. 999) {
my @num = split(//, $i);
foreach my $j (@num) {
$j **= 3;
}
if (sum(@num) == $i) {
push @numbers, $i;
}
}
I have another comment. Why did you use 'for' in one loop and 'foreach' in another? They're not different things, and you're not using the C-style loop, so there's no reason one of them should have a different name from the other.
All in all, I would rewrite this program to use far fewer temporary variables:
my @numbers = grep { sum(map { $_ ** 3 } split //) == $_ } 100 .. 999;
That might be a bit too succinct for you, but it does the same thing as yours.
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.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, 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, summary, 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?
See Writeup Formatting Tips and other pages linked from there for more info.