On Wed, 5 Oct 2011 23:44:21 -0500
Chris Stinemetz <chrisstinem...@gmail.com> wrote:

> trying to learn smart matching in an exercise.
> 
> Why does this program output "odd" when I input an even number?
> 

A few comments on your code.

> Thank you,
> 
> Chris
> 
> #!/usr/bin/perl
> 
> use warnings;
> use strict;
> 
> use 5.010;
> 
> say "Checking the number <$ARGV[0]>";
> 

You're using $ARGV[0] several times (duplicate code) and it's a positional
argument:

http://perl-begin.org/tutorials/bad-elements/#subroutine-arguments

Better unpack it as:

        my $number = shift(@ARGV);

> my $favorite = 62;
> 
> given( $ARGV[0] ) {
>         when( ! /^\d+$/ ) { say "Not a number!" }
> 
>         my @divisors = divisors( $ARGV[0] );
> 

Returns arrays as references is preferable.

Furthermore, I think you can only put when inside given and not arbitrary code,
and that "when()" operates on the datum that was given to given().

>         when( @divisors ~~ 2 ) { # 2 is in @divisors
>                 say "$_ is even";
>                 continue;
>                 }
> 
>         when( !( @divisors ~~ 2 ) ) { # 2 isn't in @divisors
>                 say "$_ is odd!";
>                 continue;
>                 }
> 
>         when( @divisors ~~ $favorite ) {
>                 say "$_ is divisible by my favorite number";
>                 continue;
>                 }
> 
>         when( $favorite ) { # $_ ~~ $favorite
>                 say "$_ is my favorite number";
>                 continue;
>                 }
> 
>         my @empty;
>         when( @divisors ~~ @empty ) { say "Number is prime" }
> 
>         default { say "$_ is divisible by @divisors" }
>         }
> 

Your indentation is erratic.

> sub divisors {
>         my $number = shift;
> 
>         my @divisors = ();

No need for the «= ()» here. An array is initialised as empty by default.

>         foreach my $divisor ( 2 .. ($ARGV[0]/2 + 1) ) {

Do you want to operate on "$number" or on "$ARGV[0]"?

>                 push @divisors, $divisor unless $number % $divisor;
>                 }
>

I got a "WTF?" moment when I saw this unless construct. I'd write it as:

if ($number % $divisor == 0)
{
        push @divisors, $divisor;
}

Regards,

        Shlomi Fish
 
> return @divisors;
> 



-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Stop Using MSIE - http://www.shlomifish.org/no-ie/

I used to be arrogant. Now I’m simply Perfect.
    — one of Shlomi Fish’s relatives.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to