Hacktoberfest - support Perl.com and Open Source

Perl Style: Closures

  • Clone similar functions using closures.

        # from MxScreen in TSA
        no strict 'refs';
        for my $color (qw[red yellow orange green blue purple violet]) {
            *$color = sub { qq<<FONT COLOR="\U$color\E">@_</FONT>> };
        }
        undef &yellow;      # lint happiness
        *yellow = \&purple; # function aliasing
    
  • Or similarly:

        # from psgrep (in TSA, or PCB 1.18)
        my %fields;
        my @fieldnames = qw(FLAGS UID PID PPID PRI NICE SIZE
                            RSS WCHAN STAT TTY TIME COMMAND);
    
        for my $name (@fieldnames) {
            no strict 'refs';
            *$name = *{lc $name} = sub () { $fields{$name} };
        }
    

Forward to Learn to Switch with for
Back to Functions as Data
Up to index

Copyright © 1998, Tom Christiansen All rights reserved.

Tags

Feedback

Something wrong with this article? Help us out by opening an issue or pull request on GitHub