http://www.perlmonks.org?node_id=278571


in reply to C pre-processor in Perl

Could someone tell me why constant is preferable to #define in the following code?

Perhaps in the case you've shown, they're more or less equivalent, but as things grow more complex, the benefits of using constant instead start to show up.

Constants are scoped to Perl packages, not to a source file, which minimizes namespace conflicts:

package Potato; use constant tuber => 1; package Peach; use constant tuber => 0; package main; print Potato::tuber, Peach::tuber;

You can also define constant references to an array or hash:

use constant visited_urls => {}; ... unless ( visited_urls->{$my_url} ++ ) { ... }

Of course, there's tricks you can pull with pre-processor macros that go beyond what use constant can do, but for simple cases like the one you show, I'd encourage you to standardize on constant instead.