in reply to Re: Associative Array Trouble
in thread Associative Array Trouble

Thank's, that worked well, except it doesn't display the last names alphabetically... I'm not quite sure what the problem is--I think it may have to do something with the keys being numbers, and we are telling it to sort by them. This is my first time using associatve arrays, so bare with me :P...anyway here's the new code:

#!/usr/bin/perl -w use strict; open(TEST, 'test.txt') || die "Couldn't open it"; print "\nFile Opened\n\n\n"; my $i=1; my %list; while(<TEST>){ chomp; /(\w+)\s+(\w+)/; print "$i : $2\,$1\n"; $list{$i} = [$1,$2]; $i+=1; } foreach my $c (sort keys %list) { print "$list{$c}->[1],$list{$c}->[0]$/"} close(TEST); die "\n\n\nFile Closed\n";

Input file:

Emmitt Smith
Walter Payton
Barry Sanders
Jim Brown
Jeremy Smith

Oh yeah, what do you mean by dereferencing?

Thanks,
Emmitt

Replies are listed 'Best First'.
Re^3: Associative Array Trouble
by tadman (Prior) on May 23, 2002 at 02:18 UTC
    Your second take is much better, much more indented, but try and keep things neat. Your closing brace in your foreach, for example, is strangely at the end of a line which is also sans-semicolon.

    Anyway, to "derefence" something is to take a reference and use it to obtain a value. References are what make people exposed to C for the first time look all green and dizzy, but they're really not that bad, especially in Perl.

    Here's a really, really brief introduction to references:
    my @array = qw[ 1 2 3 ]; my $array_ref = \@array; # Backslash makes a reference my @array_copy = @$array_ref; # @ de-references array reference $array[2] = 4; # Modifies @array directly print $array_ref->[2]; # Should be '4' now $array_ref->[1] = 5; # Modifies @array by reference print $array[1]; # Should be '5' $array_copy[1] = 6; # Modifies @array_copy, not @array print $array[1]; # Still '5'
    For a much more detailed document, check out perlref.

    Fortunately, or unfortunately depending on your opinion, Perl will automagically dereference for you in certain circumstances. Where $foo->{bar} is actually an "ARRAY" reference, you should really sub-address that as $foo->{bar}->[1] and not $foo->{bar}[1], but either should work.