in reply to Functions in Perl

Also, an example like this is very suitable for an Object Oriented application. For example:
#!/usr/bin/perl use strict; use warnings; my $example = Example->new; $example->print( map { chomp $_; $_; } <STDIN> ); $example->print('That\'s all!'); sub Example::new { my ($class, $start_num) = @_; bless \$start_num, $class; } sub Example::print { my $self = shift; print ++$$self, ": $_\n" for @_; }
-Will

Replies are listed 'Best First'.
Re: Functions in Perl
by nkuitse (Sexton) on May 23, 2004 at 15:16 UTC
    Yikes! OOP is overkill here. This is all you need:
    sub printargs { my $i = 1; printf "%d %s\n", $i++, $_ foreach @_; }

      That doesn't do what Gunth's OO code does. His code makes an object that holds the counter that keeps increasing for every call to &print. So the second time it continues where it stopped the first time. Your code has the equivalent result of throwing away the object after each use, i.e. Example::->new->(...).

      My closure example below shows the equivalent of the OO example.

      ihb

Re: Re: Functions in Perl
by ihb (Deacon) on May 24, 2004 at 14:01 UTC

    Or this can be a good example of a closure

    my $printer = do { my $c; sub { print ++$c, ": $_\n" for @_; } }; $printer->(@stuff_to_print); $printer->(@more);

    ihb