[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

Re: Associative array in perl



Hello

On Sat, 20 Jan 2001, Adityan Murthy wrote:
> Hi all,
> 
> 1. How do i create an associative array using two values: $key and $value?
Method #1

  %Hash = ('1' => 'ONE', 'A' => 'First_Alphabet');

Method #2

$Hash{'1'} = 'ONE';
$Hash{'A'} = 'First_Alphabet';

> 2. How do i check for redundant key values while creating the array?
I din't quite follow what u mean.

> 3. How do i sort the array?
@Sorted = sort(@Array);
If you want to do a numeric sort:
@Sorted = sort({$a <=> $b} @Array);

U can pass any block u want to sort (ie. instead of $a <=> $b, but the
variables should be named $a & $b).

> 4. How do i run a loop from the first value to the last using foreach and 
> access the key and the value each time?
foreach $Key (keys %Hash)
{
  print "Key ->$Key<- Value ->$Hash{$Key}<-\n";
}


If u're just beginning to perl, u're likely to have more questions. The
best documentation are the man pages. 'man perl' would give u info. about
the other man pages. 'man perlfunc' would give details about using each
function.

U may also get the Perl book from O'Reilly (well known as the Camel Book -
by Larry Wall & Randal Schawartz), but I found most of it's straight from
the man pages. Neverthless, it'd be useful.

Sreeji