Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sub outer
- {
- my $a = 123;
- sub inner
- {
- print $a, "n";
- }
- # At this point, $a is 123, so this call should always print 123, right?
- inner();
- $a = 456;
- }
- outer(); # prints 123
- outer(); # prints 456! Surprise!
- sub outer
- {
- my $a = 123;
- my $inner = sub
- {
- print $a, "n";
- };
- # At this point, $a is 123, and since the anonymous subrotine
- # whose reference is stored in $inner closes over $a in the
- # "expected" way...
- $inner->();
- $a = 456;
- }
- # ...we see the "expected" results
- outer(); # prints 123
- outer(); # prints 123
- sub find_files
- {
- my @files;
- my $wanted = sub
- {
- if($something)
- {
- push @files, $File::Find::name;
- }
- };
- # The find() function called here is imported from File::Find
- find({ wanted => $wanted }, $directory);
- return @files;
- }
- #!/usr/bin/perl
- use strict;
- use warnings;
- sub generate_multiplier {
- my ($coef) = @_;
- return sub {
- my ($val) = @_;
- $coef * $val;
- }
- }
- my $doubler = generate_multiplier(2);
- my $tripler = generate_multiplier(3);
- for my $i ( 1 .. 10 ) {
- printf "%4d%4d%4dn", $i, $doubler->($i), $tripler->($i);
- }
- __END__
- C:Temp> v
- 1 2 3
- 2 4 6
- 3 6 9
- 4 8 12
- 5 10 15
- 6 12 18
- 7 14 21
- 8 16 24
- 9 18 27
- 10 20 30
- sub Foo { stuff() }
- BEGIN { *Foo = sub { stuff() } } # essentially equivalent
- use 5.010;
- use strict;
- use warnings;
- sub make_iterator {
- my @list = @_;
- return sub { shift @list }; # new sub that 'remembers' @list
- }
- my $iter1 = make_iterator( 0 .. 10 );
- my $iter2 = make_iterator( 'a' .. 'z' );
- say $iter1->(); # '0'
- say $iter1->(); # '1'
- say $iter2->(); # 'a'
- my @sorted_array = sort { $a <=> $b } @array;
- use strict;
- use warnings;
- sub xx {
- my $zz=1;
- sub yy {
- print $zz;
- }
- }
- perl tmp.pl
- Variable "$zz" will not stay shared at tmp.pl line 8.
- # jump table to subroutines / variables
- my %jump = (
- id => 'id',
- xid => 'xid',
- hex_id => 'xid',
- h => &h,
- mac => &mac,
- sed => &sed,
- make => &make,
- nsis => &nsis,
- perl => &perl,
- dump => &perl,
- yaml => &yaml,
- yml => &yaml,
- json => &json,
- js => &json,
- help => &help,
- usage => sub{
- require Pod::Usage;
- Pod::Usage::pod2usage(
- "run perldoc $0 or pod2text $0 for more information"
- );
- }
- );
Add Comment
Please, Sign In to add comment