views:

77

answers:

1

Hi,

I am currently adding some unit tests to some legacy code and I find myself with the need to override an open function. The live code looks something like this.

if ( !open( F, $filetoopen) ){
    # do stuff with <F>
}

What I want to do is make sure that "F" contains a file handle that I have provided from my tests rather than what it thinks its opening.

I have the following code in my .t file...

BEGIN {
    *CORE::GLOBAL::open = sub { open(F,$testfiletoopen); };
};

... it does work and the code in test finishes up reading from my test file. However it will only continue to work as long as I use the same filehandle name "F" as the code in test.

If there a way to make this test code less fragile so that if the filehandle name is changed in the live code the test won't fail?

Thanks

+7  A: 

Why don't you simply use the parameters your live code provides to open?

BEGIN {
    *CORE::GLOBAL::open = sub { open $_[0], $newfilename };
};

Keep in mind that this will break horribly as soon as you use the three-argument-form of open. If anything, this question offers yet more prove that the three-argument version is superior.

innaM
Thanks thats nearly what I need sub {open (@_[0],$newfilename) }; works
Vagnerr
Ah! Now I get it. I'll edit my answer accordingly.
innaM
Agreed, you should use the three argument form of open, and use lexical file handles: ... sub { open $_[0], $_[1], $newfilename }
Ether