Multiple package VERSION declarations

I’m re-reading the parts of Intermediate Perl where we introduce packages. Perl v5.12 introduced an expanded package syntax to include a version and a block:

package Foo { ... }
package Foo 1.23;
package Foo 1.23 { ... }

That almost seems to imply that you’d have to completely define the package inside the block if you use a block, but as you know from everything else you’ve experienced in the language, Perl is happy to let you muck with other things. You can add to the package later:

use v5.12;
use warnings;
package Foo { ... }
...;
package Foo { ... }

The next package declaration does not replace the previous one, although what you do in the block might redefine subroutines or change variable values.

I was curious what happens when I use different versions with multiple package statements:

use v5.12;
use warnings;

package Foo 1.23 {
	sub foo123 {
		say "I'm in ", Foo->VERSION;
		}
	}

package Foo 1.22 {
	sub foo122 {
		say "I'm in ", Foo->VERSION;
		}
	}

package Foo {
	sub foo {
		say "I'm in ", Foo->VERSION;
		}
	}

package Foo;

foo();
foo122();
foo123();

Perhaps unsurprisingly, the last one wins:

I'm in 1.22
I'm in 1.22
I'm in 1.22

The new syntax is really just a shortcut for setting the package $VERSION. The last value it gets is the value it keeps, just like any other variable. It might be nice to have a warning for a version mismatch, but practically, there’s not much we can do with the version. We can’t, for instance, define several, separate versions of the package in the code application then decide which one to load later (or even load multiple separate versions).

Leave a Reply

Your email address will not be published. Required fields are marked *