On 21/07/2011 05:34, H Kern wrote:
Just a followup on that last one...

I'm using this code thinking that ($header{"info}) will be an array of
all the elements in the string that was read in.

The first print statement does what I hope, printing out the elements of
that array as a string.

But, when the perl compiler gets to the second print statement, it balks.

"Can't use string ("HDR QuickBooks Premier Version 2"...) as an ARRAY
ref while "strict refs" in use at..."

This makes me think that in the fourth line '( $header{"info"} ) =
split(/\t\n/, <>);' $header{"info"} is actually getting set to a string
of the concatenation of the parts split apart by the split function. Is
this true?

If so, then how do I set the hash table element header{"info"} to be the
array of elements created by the split() function?

... and, can the elements of that array be accessed using the syntax I
use in the second print statement?

Thanks, --H

code:

my %header;

( $header{"keys"} ) = split(/\t\n/, <>);
( $header{"info"} ) = split(/\t\n/, <>);

print $header{"info"} . "\n";
print $header{"info"}[0] . "\n";

You are misinterpreting what your code is doing. The values of a hash
can only be scalar values (string, number, reference or undef). The
split call is splitting the input line wherever there is a tab followed
by a newline, which is probably nowhere so you are compying the entire
input line as an unbroken string to the hash.

It is common practice to remove the trailing newline from an input
record using chomp, after which you need only split on tabs.

However, because the hash will only take a scalar, it will not hold a
list of values and instead you will have to build an anonymous array and
put a reference to it in the hash, like this:

  my $line = <>;
  chomp $line;
  $header{keys} = [ split /\t/, $line ];

  $line = <>;
  chomp $line;
  $header{info} = [ split /\t/, $line ];

Or, more concisely

  for my $key ('keys', 'info') {
    my $line = <>;
    chomp $line;
    $header{$key} = [ split /\t/, $line ];
  }

and then your second print statement will work as it is. The first,
however, would have to be written as something like

  print "@$header{info}\n";

The whole issue if references is not a simple one, and you have chosen a
non-trivial task to start programmin Perl. The whole story is laid out
in the documentation in

  perldoc perlreftut

and

  perldoc prelref

Good luck!

Rob


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to