Jamie Risk wrote:
>
> Okay, it's 5:25pm and I started programming PERL shortly after downloading
> the 5.8.0 tarballs at 2:30pm.
> I'd like to create a hash from a text file that has name/value pairs, one
> per line. So far, I'm only capable of reading it in as a list - this PERL
> stuff really seems easy - but can I (excuse the c lingo) 'cast' or refer to
> my list (@desc) as a hash somehow?
You could but you probably want to use a hash instead. Unless the keys
are not unique because perl's hash keys have to be unique.
my %hash;
$hash{one} = 1;
# creates a key 'one' with the value 1
$hash{one} = 'one';
# oops, overwrote the value 1 with 'one'
BTW, @desc is an array NOT a list
perldoc -q "What is the difference between a list and an array"
> I've got this so far:
>
> vvvv
> #!/usr/bin/perl -w
>
> if (0 > $#ARGV)
> {
> print "Need a file (or files) describing where to find states and
> stimuli.\n";
> exit;
> }
It is more idiomatic to use an array in a scalar context then to use the
index of the last element in the array.
die "Need a file (or files) describing where to find states and
stimuli.\n"
unless @ARGV;
> foreach my $state_machine (@ARGV)
Perl provides a built-in mechanism for reading from all the files on the
command line.
while ( <> ) {
This will open each file on the command line and put the current line in
the $_ variable.
> {
> chomp $state_machine;
It is VERY unlikely that command line input will be terminated with a
newline as the shell splits the arguments on whitespace.
> print "Processing the file \"$state_machine\"\n";
> open SM_FILE, $state_machine || die "can't open \"$state_machine\": $!\n";
This will be parsed by perl as:
open SM_FILE, ( $state_machine || die "can't open \"$state_machine\":
$!\n" );
Which means that the die() will only execute if the value of
$state_machine is false. You need to use the low precedence 'or' or use
parenthesis to set the correct precedence.
> while (<SM_FILE>)
> {
> chomp;
> unshift (@desc, split);
If you know that the keys will be unique then use a hash:
my ( $key, $val ) = split /=/;
$hash{ $key } = $val;
If not then you could use an array of arrays:
push @array, [ split /=/ ];
> }
>
> foreach my $key (@desc)
> {
> print $key, "\n";
> }
>
> close SM_FILE || die "this is wierd, can't close \"$state_machine\":
> $!\n";
> }
> ^^^^
>
> The "foreach my $key(@desc)" I'd prefer to be something like:
> foreach my $key (sort(keys(%desc)))
> {
> print $key,'=',$desc{$key};
> }
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]