Re: C-Style Struct?
by BrowserUk (Patriarch) on Aug 08, 2012 at 13:48 UTC
|
my %thing = ( name => 'thing', count => 0, list => [] );
++$thing{ count };
print $thing{ name };
print $thing{ list }[ 123 ];
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
| [reply] [d/l] |
|
|
| [reply] |
Re: C-Style Struct?
by Anonymous Monk on Aug 08, 2012 at 13:47 UTC
|
| [reply] |
Re: C-Style Struct?
by xiaoyafeng (Deacon) on Aug 08, 2012 at 14:02 UTC
|
In general, You don't need to create C-style struct in perl in favor of a hash. But There is indeed several ways to do this, below is one of those:
package C_struct;
sub new{
my $self = shift;
return bless {'counting_number' => shift,
'name' => shift,
'stuff_list' => shift
}, $self;
}
package main;
use Data::Dumper;
my $cc = C_struct->new(123,'bb', [1,2,3]);
my $dd = C_struct->new(234,'cc', [2,3,4]);
print $cc->{name};
print $dd->{name};
print Dumper $dd->{stuff_list};
1;
Always as a alternative, you can searcg modules on CPAN to reach what you want instead of doing it by hand.
UPDATE
modify code to be more intuitive.
I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction
| [reply] [d/l] |
|
|
Your code example doesn't allow access by name, so what's the advantage of it?
| [reply] |
|
|
sub count {
my $self = shift;
return $self->[0] unless @_;
$self->[0] = shift;
}
# ...
$cc->count(42);
print $cc->count;
| [reply] [d/l] |
|
|
changed it, Thanks for your reminding.;)
I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction
| [reply] |
|
|
|
|
Re: C-Style Struct?
by influx (Beadle) on Aug 08, 2012 at 18:51 UTC
|
sub struct {
my ($name, %args) = @_;
localscope: {
# we want to mangle the symbol table
# so set 'no strict refs'
no strict 'refs';
foreach my $a (keys %args) {
*{"${name}::${a}"} = sub {
my ($class, $val) = @_;
# val means it needs updating
if ($val) {
nowarning: {
no warnings 'redefine';
*{"${name}::${a}"} = sub {
$val;
};
} # end nowarning
return $val;
}
return $args{$a}
};
}
} # end localscope
}
# Create a new struct
struct 'Player' => (
count_var => 0,
name => 'Zork',
list_of_stuff => ['a', 'b']
);
print Player->name;
# you can update a value in this "struct", like so
Player->name('Zippy');
| [reply] [d/l] |
|
|
| [reply] |
Re: C-Style Struct?
by Mr. Newb (Acolyte) on Aug 08, 2012 at 13:57 UTC
|
To BrowserUK, I ran your code, the output is just 'thing'. I would expect it to print 123. What does that line
( print $thing{ list }[123]) do? | [reply] [d/l] |
|
|
| [reply] |
|
|
My self has few answers, that's why I come here. How would I iterate through the array $thing{list}? ie, what would I write for a foreach loop?
| [reply] [d/l] [select] |
|
|