tags:

views:

89

answers:

2

I have a text file, and a function to retrieve from that text file:

@thefile = read_file( 'somepathfile' );

I would like to have a different implementation of the read_file function depending on which type is receiving the information.

So if I write:

%thefile = read_file( 'somepathfile' );

then a different function will be executed.

How do I do that?

+5  A: 

Have a look at Want or Contextual::Return CPAN modules.

Below is a simple example using 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') };

NB. The hash dereference is needed to force the return context.

/I3az/

draegtun
is there any way of doing this without the %{} around hash calls?
Hermann Ingjaldsson
this is a solution, a suboptimal solution but nevertheless, a solution.
Hermann Ingjaldsson
Not really. Perl only understands scalar, list or void contexts so heaven knows what hoops the Want module has to goes through. Personally I prefer to be more implicit with my contexts and would go for something like Sinan's answer or perhaps an object. for eg. MyFile->read('file.txt')->as_list (see gist: http://gist.github.com/487366)
draegtun
to install in shell:sudo apt-get install libwant-perl
Hermann Ingjaldsson
`Personally I prefer to be more implicit with my contexts` - oops that should be "explicit" :)
draegtun
+10  A: 

While draegtun's answer illustrates a nice technique, I am going to recommend clarity. For example:

@thefile = read_file_lines( 'somepathfile' );

%thefile = read_file_pairs( 'somepathfile' );
Sinan Ünür
To put it more directly: Don't synthesize a new "hash" context on top of the scalar/list/void contexts that Perl already has. It's un-perlish and will confuse people.
Michael Carman
yes but the original purpose was to use just a single function to read from the file. the function would then find out what is receiving and act accordingly.
Hermann Ingjaldsson