I am processing different types of files, some compressed and some uncompressed. The uncompressed ones I can open with just

open(HANDLE, $filename) or die ...

and the compressed ones with

open(HANDLE, "$unzip $unzip_opts $filename |") or die ...

These two different ways of opening a file are in two different sub's - _open_unzipped and _open_zipped

I also have a sub called _detect_type that uses some logic to work out which open routine is required. And it returns a reference to the required sub

sub _detect_type { ... # logic to determine type return \&_open_unzipped if $rule1; return \&_open_zipped if $rule2; return undef; }

All of this is wrapped up in a module Import.pm (shocking name I know ...)

package Import; use Exporter; @ISA = qw(Exporter); @EXPORT = qw(load_file); @EXPORT_OK = qw(_detect_type _open_zipped _open_unzipped ); %EXPORT_TAGS = {STD => \@EXPORT, TEST => \@EXPORT_OK }; sub load_file { my $filename = shift; my $openner = _detect_type($filename); &$openner($filename); while (my $line = <HANDLE>) { ... # do stuff with lines } } sub _detect_type {...} sub _open_zipped {...} sub _open_unzipped {...} 1;

Furthermore, I am a good little vegemite and I have a test harness for all this in t/Import.t

use Test::More qw(no_plan); use Import qw(:TEST); ... is($test1, $result1); is($test2, $result2); ...

Now to my problem - how do I check which code reference I got back from _detect_type.

This doesn't always work - sometimes the code reference matches and sometimes it doesn't.

is(_detect_type('unzipped.txt'), \&open_unzipped); is(_detect_type('zipped.zip'), \&open_zipped);

Is what I am doing unreasonable - or fraught with issues?

I am using Perl 5.6.0 on RH 6.2 Linux.


In reply to Comparing references to sub's by leriksen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.