At 02:41 PM 2/1/02 -0800, Tarak Parekh wrote: >Hello, > >I am trying to use Objects in Perl, and am having some basic problem. >I am sure I am missing something, but am not able to figure out what. > >--- > >package A > >use strict;
Good. Lots of people don't bother to put this in modules. >my @arr; > >sub new >{ > my $classname = shift; > my $self = { > 'cfg_file' => undef, > @_, > }; > > # Mark it of the right type > bless ($self, $classname); > > # Initialize the arrays > my $i = 0; > for ($i = 0; $i < 4; $i += 1) { > $arr[$i] = $i; > } > > return $self; >} > >sub num_get >{ > my $self = shift; > my ($type) = @_; > > eval { > no strict ; > return $#type; > } >} The fact that you had to put "no strict" in should have been a clue. NEVER disable strictness unless you know WHY Perl's complaining. In this case, $#type is the index of the last entry of the array @type. You don't have one, so without strictness, it doesn't mind, just treats it as an empty array, hence the -1. If you want to return the number of entries in the array, you'd need to do sub num_get { my $what = pop; eval "$#$what"; } although that is rather perilous since it lacks checking. ("num" isn't a good name anyway since it returns the last index, rather than the number of entries, but never mind.) Refer to the recent discussion on this list about alternatives to using symbolic names. This would be better done using a hash. Here's something to consider: package A; my %classdata; sub new { my ($class, %arg) = @_; $classdata{delete $arg{name}} = delete $arg{value}; return bless { cfg_file => 'undef', %arg }, $class; } sub num { my $what = pop; return exists $classdata{$what} ? scalar @{$classdata{$what}} : undef; } >--- Client code > >use A; > >my $try = A -> new ("something"); > >print $try -> num_get ('arr'); my $try = A->new(name => 'arr', value => [1 .. 17]); print $try->num('arr'); >--- >The client code always prints -1. > >When I try debugging the code, arr looks good in the for loop in the >'new' function, but after coming out of the for loop it shows nothing. > >Could someone thrown light on this ? -- Peter Scott Pacific Systems Design Technologies http://www.perldebugged.com -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]