Perl函数知道接收器类型

Her*_*son 2 perl function

我有一个文本文件,以及从该文本文件中检索的函数:

@thefile = read_file( 'somepathfile' );
Run Code Online (Sandbox Code Playgroud)

我想read_file根据接收信息的类型有不同的函数实现.

所以,如果我写:

%thefile = read_file( 'somepathfile' );
Run Code Online (Sandbox Code Playgroud)

然后将执行不同的功能.

我怎么做?

Sin*_*nür 12

虽然draegtun的答案说明了一个很好的技术,但我将推荐清晰度.例如:

@thefile = read_file_lines( 'somepathfile' );

%thefile = read_file_pairs( 'somepathfile' );
Run Code Online (Sandbox Code Playgroud)


dra*_*tun 6

看看WantContextual::ReturnCPAN模块.

以下是一个使用的简单示例Want:

use strict;
use warnings;
use Want;

sub read_file {
    my $filepath = shift;
    my @file_contents = get_file_contents($filepath);

    return @file_contents if want('LIST');

    return { 
        filepath => $filepath, 
        content  => \@file_contents, 
        lines    => scalar @file_contents 
    } if want('HASH');

    die "Nothing for that context!";
}

my @list = read_file('foo');
my %hash = %{ read_file('foo') };
Run Code Online (Sandbox Code Playgroud)

NB.需要哈希取消引用来强制返回上下文.

/ I3az /