use of field pragma in Perl

Perl LogoIt happens many times that you declare a variable name something and calling that variable name by something else. In case of hash in perl, calling that variable or assigning that variable will not give error. It will silently create that key value pair. This is called autovivification.

For ex:
my $name = "Jassi";
$self->{name} = "Sanjeev aka Jassi"  # it will work as it is
$self->{Name} = "Jaiswal";                    # It will silently create another key value pair.
# Now if you try to access $self->{name}, it will not give you
#Jaiswal. You will get "Sanjeev aka Jassi".

At above example you can see that our motto was to change the value of key “name” but by mistake we wrote “Name”, then also it got updated without any error. So being a human being, we do such typo mistakes and It will be very tough for us to find such bugs.

Before writing a program, lets keep in mind that what variables we are going to use and strict the program to use those variable name only. If I use any other variable than provided one, it should throw error. For this purpose we use “field” pragma.

package Student;

# You may like to give a list of attributes that are only allowed, and have Perl should exit with an error,
#if someone uses an unknown attribute.
# You can do this using the fields pragma i.e use fields fieldname1, fieldname2 etc”
# Isn’t it nice feature to secure our code.
use fields ‘name’,

sub new {
my($class, $name) = @_;
$self = fields::new($class);    # returns an empty “strict” object
$self->{name} = $name;        # attributes get accessed as usual
return $self;                              # $self is already blessed

my $classname = Student->new(‘Jassi’);
$classname->{name} = ‘Jassi D\’Costa’;  # works
$classname->{Name} = ‘foo’;  # blows up. If I will not use field pragma, It will silently create this key value pair

# for    $classname object.
# End of the program

Here is the screen-shot of the error that you will get.

Sanjeev Jaiswal

He loves web programming and security and co-founder of Alien Coders. He usually shares and helps engineering students and IT professionals in academics and jobs. An avid reader and quick learner.

Share your comment

%d bloggers like this: