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??

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.