This seemed like it would be easy when I decided to do it but it turned out to be a bit more difficult than I would have thought.

Basically, I've got a file.

data.txt

that is full of data formatted like this

name|value

and in side a script i've got a hash

%stuff (

);

I want the data to go inside the hash.

I've done this and dozens of other variations

open (OUT, "data.txt") || die "Can't open the data file";


foreach $i ($data[0], $data[1]){
  chomp($i);
  ($short,$place) = split(/\|/,$i);


         %stuff = (
                          '$short' => '$place',

                        );  

   close(OUT);

}

While there are no errors that are obvious with in the scripts performance, the desired outcome does not happen.

short is supposed to filter to place.

Think of it as a word filter..

Now, it works perfectly when I actually have the hash data there in this format

'short' => 'place',

but I can't get it to properly read and covert from the data file.

Any suggestions or ideas on what I'm doing wrong?

Thanks in advance.

Recommended Answers

All 2 Replies

You seem to have skipped the basics of perl. The biggest problem is using single-quotes around your scalar variables, which will not interpolate them but treat them as literal strings. You almost never quote a lone scalar variable anyway. Assuming $data[0] and $data[1] are properly defined:

my %stuff = ();
foreach my $i ($data[0], $data[1]){
  chomp($i);
  my ($short,$place) = split(/\|/,$i);
  $stuff{$short} = $place;
}

I assume this is what you are actually trying to do:

my %stuff= ();

open (OUT, "data.txt") || die "Can't open the data file";
while (my $line = <OUT>) {
   chomp $line;
   my ($short,$place) = split(/\|/,$line);
   $stuff{$short} = $place;
}  
close OUT;

foreach my $key (keys %stuff) {
   print "$key = $stuff{$key}\n";
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.