Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Javascript to Perl = fail

by JavaFan (Canon)
on May 04, 2012 at 22:36 UTC ( #968999=note: print w/replies, xml ) Need Help??


in reply to Javascript to Perl = fail

sub isprime($) { my $num = $_[1]; $primer = 1; $ValidChars = "2357"; $str = $num; if (index($ValidChars, ord(substr $str, 0, 1)) == 1) { $primer = 0; } return $primer; }
That returns 1 unless the first character of the first argument (assuming you fix the already noticed error regarding $_[1]) equals 3. I think you are calling isprime only with single digit numbers, and want to return if the digit is a prime number. I'd write that as:
sub isprime {$_[0] =~ /^[2357]$/}
although I would fix the name. Or just inline the test -- that's a lot clearer than any name I can think of.
if (($n != 1) && ($n != 0)) { if (isprime($n)) { $prime += $n; } if (!isprime($n)) { $comp += $n; } }
Too many ifs, and too many calls to isprime. I'd write that as:
if ($n =~ /^[2357]$/) { $prime += $n; } elsif ($n !~ /^[01]$/) { $comp += $n; }
Or, when I'm in the mood for something funky, as a ternary returning an lvalue.
$text.length
That should be spelled length($text).

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://968999]
help
Chatterbox?
[moritz]: depends on what you mean by "most stuff"
[1nickt]: I am sure I don't know about most of the stuff that is no longer controlled by humans. I do know that it's past the point of determining consumer pricing and into things that can kill me with blunt force!
[holli]: but is this really a problem 1nickt? Nobody knows how your human taxi drivers brain works either
[holli]: at least for cars, if the ai works better than a human on average, by all means let the machines drive

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2017-11-21 13:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (301 votes). Check out past polls.

    Notices?