Perllace has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have a code in a package called Device.pm
sub new { my ($class,$device,$serveraddr,$port) = @_; my $self = {}; bless ($self,$class); $self = { 'device' => $device, 'serveraddr' => $serveraddr, 'port' => $port };

THe same module, needs to take care of creating an object of another package, for this I need to pass the values of serveraddr and port, how do I do that ?

for ex, (I know this is wrong,I get Global Symbol $self,$serveraddr,$port requires explicit package name error)
my $SockObj = Communication->new( $self->{$serveraddr}, $self->{$port} +);
Communication.pm inturn contains
sub Communication::new { my $class = shift; my ($addr, $port) = @_; my $socket = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $addr, PeerPort => $port, ) or die "couldn't connect: $!"; $socket->autoflush(); return bless $socket, $class; }
Any advice would be very helpful. Thanks, Perllace

Replies are listed 'Best First'.
Re: How to send attributes of an object to create an object of another class?
by wfsp (Abbot) on Apr 06, 2011 at 11:16 UTC
Re: How to send attributes of an object to create an object of another class?
by chromatic (Archbishop) on Apr 06, 2011 at 23:19 UTC
    I know this is wrong...

    It's right, but it's only right within a method where $self is an instance of Device. This means you have to write something like:

    package Device; sub create_communication { my $self = shift; return Communication->new( $self->{$serveraddr}, $self->{$port}; } package main; my $device = Device->new( 'device', 'localhost', 8080 ); my $communication = $device->create_communication();
Re: How to send attributes of an object to create an object of another class?
by Anonymous Monk on Apr 06, 2011 at 10:11 UTC
    #!/usr/bin/perl --- use strict; use warnings; use Data::Dumper qw' Dumper '; Main( @ARGV ); exit( 0 ); sub Main { my $variable = 'String'; my %Hash = ( $variable => 'Hello' ); my $Ref = \%Hash; $Ref->{STRING} = 'STRING'; $Ref->{'s'.'t'.'r'.'i'.'NG'} = 'striNG'; $Hash { $Ref->{$variable} } = 'World!'; print Dumper( \%Hash ), "\n\n"; } __END__ $VAR1 = { 'String' => 'Hello', 'Hello' => 'World!', 'striNG' => 'striNG', 'STRING' => 'STRING' };
    I suggest reading through perlintro and References quick reference