Tuesday, April 25, 2006

Perl : map() with your subroutines

You can use map function with your subroutines as well. Have a look at the following example.

Code:

## subroutine that returns double of a number (or whatever passed to it as an argument :-)
sub double_it{
        2*$_;
}

@nums = (1 .. 10); # array containing numbers 1 to 10
@doubles = map(&double_it, @nums); ## using map to create @doubles with subroutine double_it

$\=" "; # $\ is the built-in variable to specify the output record separator.

        for(@doubles){

        print;
        }

Output:

2 4 6 8 10 12 14 16 18 20

2 comments:

Anonymous said...

This one is interesting functionality. It will definitely reduce developers time. I hope in next version of java they will add this functionality.
Shrinivas

Ketan said...

If you have perl installed on your machine, you try out some more examples with map that you can think of. Perl is really enjoyable ! A few lines of code do wonders. In Java, you have to code everything... for complex things is could be good but for small tasks there's no match for Perl.