What's the best Perl practice for returning hashes from functions?

后端 未结 7 1934
走了就别回头了
走了就别回头了 2021-02-04 07:31

I am mulling over a best practice for passing hash references for return data to/from functions.

On the one hand, it seems intuitive to pass only input values to a fun

7条回答
  •  醉梦人生
    2021-02-04 08:10

    My personal preference for sub interfaces:

    1. If the routine has 0-3 arguments, they may be passed in list form: foo( 'a', 12, [1,2,3] );
    2. Otherwise pass a list of name value pairs. foo( one => 'a', two => 12, three => [1,2,3] );
    3. If the routine has or may have more than one argument seriously consider using name/value pairs.

    Passing in references increases the risk of inadvertent data modification.

    On returns I generally prefer to return a list of results rather than an array or hash reference.

    I return hash or array refs when it will make a noticeable improvement in speed or memory consumption (ie BIG structures), or when a complex data structure is involved.

    Returning references when not needed deprives one of the ability to take advantage of Perl's nice list handling features and exposes one to the dangers of inadvertent modification of data.

    In particular, I find it useful to assign a list of results into an array and return the array, which provides the contextual return behaviors of an array to my subs.

    For the case of passing in two hashes I would do something like:

    my $foo = foo( hash1 => \%hash1, hash2 => \%hash2 ); # gets number of items returned
    my @foo = foo( hash1 => \%hash1, hash2 => \%hash2 ); # gets items returned
    
    sub foo {
       my %arg = @_;
    
       # do stuff
    
       return @results;
    }
    

提交回复
热议问题