icon Top 9 categories map      RocketAware > Perl >

How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regexp}?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    

How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regexp}?

With the exception of regexps, you need to pass references to these objects. See Pass by Reference for this particular question, and the perlref manpage for information on references.

Passing Variables and Functions
Regular variables and functions are quite easy: just pass in a reference to an existing or anonymous variable or function:

    func( \$some_scalar );

    func( \$some_array );
    func( [ 1 .. 10 ]   );

    func( \%some_hash   );
    func( { this => 10, that => 20 }   );

    func( \&some_func   );
    func( sub { $_[0] ** $_[1] }   );

Passing Filehandles
To create filehandles you can pass to subroutines, you can use *FH or \*FH notation (``typeglobs'' - see the perldata manpage for more information), or create filehandles dynamically using the old FileHandle or the new IO::File modules, both part of the standard Perl distribution.

    use Fcntl;
    use IO::File;
    my $fh = new IO::File $filename, O_WRONLY|O_APPEND;
                or die "Can't append to $filename: $!";
    func($fh);

Passing Regexps
To pass regexps around, you'll need to either use one of the highly experimental regular expression modules from CPAN (Nick Ing-Simmons's Regexp or Ilya Zakharevich's Devel::Regexp), pass around strings and use an exception-trapping eval, or else be be very, very clever. Here's an example of how to pass in a string to be regexp compared:

    sub compare($$) {
        my ($val1, $regexp) = @_;
        my $retval = eval { $val =~ /$regexp/ };
        die if $@;
        return $retval;
    }

    $match = compare("old McDonald", q/d.*D/);

Make sure you never say something like this:

    return eval "\$val =~ /$regexp/";   # WRONG

or someone can sneak shell escapes into the regexp due to the double interpolation of the eval and the double-quoted string. For example:

    $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger';

    eval "\$string =~ /$pattern_of_evil/";

Those preferring to be very, very clever might see the O'Reilly book, Mastering Regular Expressions, by Jeffrey Friedl. Page 273's Build_MatchMany_Function() is particularly interesting. A complete citation of this book is given in the perlfaq2 manpage.

Passing Methods
To pass an object method into a subroutine, you can do this:

    call_a_lot(10, $some_obj, "methname")
    sub call_a_lot {
        my ($count, $widget, $trick) = @_;
        for (my $i = 0; $i < $count; $i++) {
            $widget->$trick();
        }
    }

or you can use a closure to bundle up the object and its method call and arguments:

    my $whatnot =  sub { $some_obj->obfuscate(@args) };
    func($whatnot);
    sub func {
        my $code = shift;
        &$code();
    }

You could also investigate the can() method in the UNIVERSAL class (part of the standard perl distribution).


Source: Perl FAQ: Perl Language Issues
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How do I create a static variable?

Previous: What is variable suicide and how can I prevent it?



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: PERL




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq7/How_can_I_pass_return_a_Functio.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments