Vishnu wrote:
I was going through the book intermediate perl and came across the
following code.

my @odd_digit_sum = grep digit_sum_is_odd($_), @input_numbers;

sub digit_sum_is_odd {
        my $input = shift;  ------------> what are we doing here?
        my @digits = split //, $input;  # Assume no nondigit
characters
        my $sum;
        $sum += $_ for @digits;  ---------> what exactly is the
operation performed here? specially haven't understood "for"
        return $sum % 2;
}

Appreciate your inputs.

If you start out with the array:

my @input_numbers = ( 123, 234, 345, 456 );

Then the expression:

my @odd_digit_sum = grep digit_sum_is_odd($_), @input_numbers;

Will pass each element of @input_numbers in turn to the digit_sum_is_odd() subroutine and if the subroutine returns TRUE will then pass that element on through to the @odd_digit_sum array. In the end the @odd_digit_sum array will contain the elements 234 and 456.


The first line of the subroutine:

        my $input = shift;

Is short for:

        my $input = shift @_;

Because in a subroutine the arguments to a subroutine are passed through the @_ array and shift() removes the first element of that array and returns it which is then assigned to the $input variable.


        my @digits = split //, $input;

This converts, for example, the number 123 to the string '123' and splits it into individual characters '1', '2' and '3' and assigns that list to the array @digits.


        my $sum;

This creates a lexically scoped variable which is only visible inside the subroutine.


        $sum += $_ for @digits;

This uses the _for_ statement modifier, which is similar to the _foreach_ loop:

        foreach ( @digits ) {
            $sum += $_;
        }

This loops over the elements of @digits and assigns each element in turn to the $_ variable. Each element in turn is then added to the $sum variable. So, for example, if @digits contains ( '1', '2', '3' ) then the sum of those digits is 6.


        return $sum % 2;

Finally modulus is performed on the $sum value. $sum % 2 will return 0 (FALSE) if $sum is divisible by 2 (even) or 1 (TRUE) if $sum is NOT divisible by 2 (odd).



John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

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