0

Is it possible to have a hash as a data member of a perl object? If so,what is the syntax?? And also how to assign values to this hash??

2
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by laddu
0

Hi,

Is it possible to have a hash as a data member of a perl object?

YES.

If so,what is the syntax?? And also how to assign values to this hash??

Well let me tell you the simplest method to create and assign the hash dynamically, on demand.
There are two simplest method,
1. Creating an anonymous hash

sub new_Employee
{
	my ($name, $age, $position) = @_;
	# create an anonymous hash
	my $$r_emp = {
			name => $name, 
			age =>$age, 
			position => $position
		};
	return $r_emp		# return object
}

2. Or, returning a reference to local variable.

sub new_Employee
{
	my ($name, $age, $position) = @_;
	# create an anonymous hash
	my %$r_emp = (
			name => $name, 
			age =>$age, 
			position => $position
		);
	return \%r_emp		# return object
}

Use it to create two employees.

$emp1 = new_Employee('XYZ', 25, 'Software Developer');
$emp2 = new_Employee('ABC', 35, 'Web developer');


The Object-oriented approach:

To create objects you need to create package in Perl. This is how the object-oriented programming is accomplished in Perl.

package NewEmployee;
# NewEmployee.pm
sub new
{
	my ($name, $age, $position) = @_;
	my $r_emp = {
			name => $name;
			age => $age;
			position => $position;
		};
	return $r_emp;
}

sub promote
{
	my $r_emp = shift;
	# do some operation, like assign the new position to the employee
	...
}

Note:
You need to save the NewEmployee.pm in you 'lib' folder

Use it to create employee.

use NewEmployee;
# test_newemp.pl
$emp = NewEmployee::new('DEF', 40, 'Design Manager');
NewEmployee::promote($emp);

Hope this helps you...

kath.

0

Thanks a lot for your short tutorial, it was really very helpful :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.