Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

After breaking up a file line by line into array elements. We'll just call the array values $test_name and $test_number for now. Can I created a hash list by taking each element for each line:
%hash1 = ($key=>i++;$test_name=>$element_one,$test_num=>$element_two) /*element_one and two are variable names that contain string and numbe +r respectively */
and then print them by print"%hash1($test_name) \n";

Edit Masem 2001-10-12 - Code Tags and formatting

Replies are listed 'Best First'.
Re: Getting feet wet with hashes
by dragonchild (Archbishop) on Oct 11, 2001 at 21:58 UTC
    You could ... I don't suggest you do so. The idea behind a hash is to use named keys. What you really want to do is create a list of hashes, using hash references.

    Better would be to do something like:

    while (my $line = <INFILE>) { my @line = split /\t/, $line; my %hash = ( key0 => $line[0], key1 => $line[1], key2 => $line[2], key3 => $line[3], key4 => $line[4], ); print "Key 3 is $hash{key3}\n"; push @lines_of_file, \%hash; }
    However, even better would be to use a hashslice, similar to an arrayslice. That syntax would look something like:
    while (my $line = <INFILE>) { my %hash; @hash{qw(key0 key1 key2 key3 key4)} = split /\t/, $line; print "Key 3 is $hash{key3}\n"; push @lines_of_file, \%hash; }
    The two snippets produce identical results, except the second is, in my mind, easier to handle. Some prefer the first, and that's perfectly fine.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: Getting feet wet with hashes
by arturo (Vicar) on Oct 11, 2001 at 21:55 UTC

    Your syntax is incorrect, but you have the basic idea. %hash refers to the hash, $hash{$key} refers to the value contained in %hash that's associated to $key (the value is a scalar, so think of $ as referring to scalars and you'll have it. I don't know whether $key=>i++, does what you want it to (even with the correction) but assuming i is a variable, you need to add the $ to the front of it.

    Note also that hash keys occur inside curly braces {}. Final note: perl doesn't support C-style comments -- # marks the rest of a line as a comment.

    hth!

    perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'