The closest thing in Perl to the C "array of struct" is a Perl "Array of Hash".
Just like in C, normally you want to make "deep copies" of each "element of the struct". In C, you could perhaps do a malloc of some space for m_username and then copy $stg_username into that allocated memory.
In Perl this is easier. No malloc() is required. And no explicit copy is required.
If you actually DO mean a reference to a string to be used
in place of a copy of the string, then that is of course possible also. Most of the time, I use a deep copy instead of a reference to the string in Perl as it is so easy to do in Perl with just "=", malloc() and then strcpy()is not required.
\[@ary_email_address] makes no sense. [ ary_email_address ] IS a reference to anon memory with email addresses. Another thing that is different than in C, is that each type of variable has its own name space. WOW! @a,$a,sub a,%a can all co-exist in the same program. So there is no need to prefix @email_address with @ary_email_address.
I made a ArrayofHash (similar to C Array of Struct) below. In Perl, it is possible to find out whether a value is a "pointer" to an array or not and I demo'ed that below also. Also the Data::Dumper module is VERY handy - there is no such equivalent in C...also demo'd below.
Hope this helps...
#!/usr/bin/perl -w
use strict;
use Data::Dumper;
my $username = "PerlMonk";
my $password = "VeryGoodPassword";
my @email_addresses = ( "Monk1", "Monk2", "Monk3" );
my %Record1 = (
username => $username,
password => $password,
emailAddress => [@email_addresses]
);
my %Record2 = (
username => 'SomeOtherPerlMonk',
password => 'AntoherVeryGoodPassword',
emailAddress => ["monka", "monkb", "monkc"],
);
my @AoH;
push (@AoH, {%Record1}); #{%Record1} allocates new memory
#for the anonymous hash, makes a copy,
#of the whole hash table, then adds a
#reference to that anon hash
#to the array @AoH (similar to a C pointer).
push (@AoH, {%Record2});
print Dumper \@AoH;
$username = "XXXXXXXXXXXXXXXXXXXX";
# the record in AoH is unchanged because $username was copied
# into that record
#print Dumper \@AoH; #un-coment to see same thing again
print "\nDumping records....\n";
foreach my $record (@AoH)
{
foreach my $key (keys %$record)
{
if ( ref ($record->{$key}) eq 'ARRAY' )
{
print "$key => @{$record->{$key}}\n";
}
else
{
print "$key => $record->{$key}\n";
}
}
print "\n";
}
__END__
$VAR1 = [
{
'password' => 'VeryGoodPassword',
'emailAddress' => [
'Monk1',
'Monk2',
'Monk3'
],
'username' => 'PerlMonk'
},
{
'password' => 'AntoherVeryGoodPassword',
'emailAddress' => [
'monka',
'monkb',
'monkc'
],
'username' => 'SomeOtherPerlMonk'
}
];
Dumping records....
password => VeryGoodPassword
emailAddress => Monk1 Monk2 Monk3
username => PerlMonk
password => AntoherVeryGoodPassword
emailAddress => monka monkb monkc
username => SomeOtherPerlMonk
|