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

I am trying to read a line of text from a file, and use it to create an array called @list so that I can access the individual elements. The text file is called testhash.txt and at present contains a single line of text that reads:
'key1,value1','key2,value2','key3,value3','key4,value4'

The script behaves as if @list is a single line of text rather than an array. Yet if I simply copy and paste the line of text into @list like so:

@list=('key1,value1','key2,value2','key3,value3','key4,value4');

then I can do arrayish things with it. Here is my script:

#testhash.txt has a single line of text that reads: #'key1,value1','key2,value2','key3,value3','key4,value4' open(HASH,"testhash.txt"); $line=(<HASH>); chomp $line; @list=($line); @list=('key1,value1','key2,value2','key3,value3','key4,value4'); print "here is \@list:\n"; print $list[0]; print $list[3]; print "\nEnter the keycode:"; chop ($find=<STDIN>); foreach (@list) { ($keycode,$keyvalue)=split /,/; #split up the array elements if ($find=~/$keycode/i) { print "Keycode $keycode has the value $keyvalue \n"; } }

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I read a line of text from a file into an array?
by ton (Friar) on Jul 17, 2001 at 00:57 UTC
    looks to me like you should be using hashes, not arrays. I'd do something like this:
    use strict; open(HASH, "testhash.txt") || die; my $line = <HASH>; chomp $line; $line =~ s/'//g; my %hash = split(/,/, $line); print "\nEnter the keycode: "; chomp($line = <STDIN>); print "Keycode $line has the value $hash{lc($line)}\n" if ($hash{lc($l +ine)});
    Note that this will not match superstrings of valid keycodes, which your code does. I'm fairly certain that this was not your intent :)

    -Ton

    Originally posted as a Categorized Answer.