MoniqueLT has asked for the wisdom of the Perl Monks concerning the following question:

I find myself doing the same thing repeatedly so I would like to make a method with 3 different variables to pass in as the parameters. Is there a way to do this, I could not find a subroutine example online to see the correct format. The format below is wrong and it shows what I'm looking for

Thank you

example:

Extract($filename, $filepath, $regex) { do stuff }

Replies are listed 'Best First'.
Re: Subroutines with Parameters
by davido (Cardinal) on Nov 04, 2013 at 01:56 UTC

    perlsub. Even perlintro! (Spend 20 minutes reading perldoc perlintro before your next question.)

    One thing to note: Probably the best way to pass a regular expression to your subroutine is to pass a regexp object, obtained using the qr// operator described in perlop. Example:

    sub test_match { my( $regexp, $string ) = @_; return scalar( $string =~ $regexp ); } my $string = "Hello world!\n"; print $string if test_match( qr/hello/i, $string );

    Dave

Re: Subroutines with Parameters
by LanX (Saint) on Nov 04, 2013 at 00:55 UTC
    > I could not find a subroutine example online to see the correct format.

    That's hard to believe! :)

    Putting your headline into google leads to plenty of hits, among them perlsub

    example:

    sub extract{ my ($filename, $filepath, $regex) = @_; # do stuff }

    Cheers Rolf

    ( addicted to the Perl Programming Language)

Re: Subroutines with Parameters
by kcott (Archbishop) on Nov 04, 2013 at 05:05 UTC

    G'day MoniqueLT,

    You've received good advice on writing a subroutine; however, I noticed you actually wrote: "... I would like to make a method ...".

    If you want to code:

    $object->method_name($param1, $param2, $param3);

    Then your subroutine definition will typically look more like this:

    sub method_name { my ($self, $param1, $param2, $param3) = @_; ... }

    See "perlootut - Object-Oriented Programming in Perl Tutorial" for a general discussion and the Methods section for specifics.

    -- Ken