in reply to Re: Re: Link a hash and an array
in thread Link a hash and an array
But, of course, that does not work exactly like that
It would probably help if you used syntactically valid Perl code. If you did, you might be surprised to find that what you have works fine. Here I've gone through the trouble to port it for you:
#!/usr/bin/perl use strict; # safety checks use warnings; # useful hints use Data::Dumper; # notice the use of 'my' to declare a lexical scope my @Address=qw(type firstname lastname streetaddress city zip); my @Phone=qw(type name phonenumber); sub ReadStuff { # instead of using funny global variables, scope the # hash within the subroutine, and return a reference at # the end my %Stuff; # $_[0] is the first element of the array @_ # eq is the string equality test # @h{@k} = @v is the syntax for hash slices if ($_[0] eq 'addr') { @Stuff{@Address} = @_ } elsif ($_[0] eq 'phone') { @Stuff{@Phone} = @_ } # return a reference (as mentioned before) return \%Stuff; } # let's quote our list elements this time my @data1 = ('addr', 'bob', 'smith', '1234 main st', 'anytown', '20500 +'); my $stuff1 = ReadStuff(@data1); my @data2 = ('phone', 'bob', 'smith', '212-555-1212'); my $stuff2 = ReadStuff(@data2); # dump the results from both runs print Dumper $stuff1; print Dumper $stuff2;
Update: while this code does work, it doesn't quite do what your original question asks. That said, what you have here is probably exactly what I would suggest -- that is, keep the data in one place, and a list of keys in the other to tie it together. Using the structures this code creates, you could, for example, do $Stuff1->{$Address[4]} to get the field from $Stuff1 that corresponds to the key at index 4 from @Address. (whew! try saying that 5 times fast!)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Re: Link a hash and an array
by SkipHuffman (Monk) on Mar 12, 2004 at 15:45 UTC | |
|
Re: Re: Re: Re: Link a hash and an array
by SkipHuffman (Monk) on Mar 12, 2004 at 16:23 UTC | |
by revdiablo (Prior) on Mar 13, 2004 at 00:01 UTC |