in reply to Using a Hash Variable in an If Statement

Adding to toolic's code if you wanted the station name plus the run number added to the output you could do the following

#!/usr/bin/perl use warnings; #use strict; my @names = qw( DONT MICH LEON RAPH SPLN SHRD CASY APRL FOOT BEBP RKST DUBY SAMH GRAW KNYN KP01 KP02 KP03 KP04 KP05 ); my %data; open my $file, "<", "rat_event.txt" or die "Can't open file:$!"; while(<$file>) { next if /\.mcp/; chomp; my ($s, $n) = split; push @{ $data{$s} }, $n; } my $i = 1; for my $name (@names) { print "$name\n"; my $x = 1; for (@{$data{$name}}) { print "Time $x : $_\n"; $x++; } print "\n"; $i++; } close($file);

Replies are listed 'Best First'.
Re^2: Using a Hash Variable in an If Statement
by Bama_Perl (Acolyte) on May 11, 2015 at 20:51 UTC
    I apologize for the many questions, but what does the  print "$_\n" for @{ $data{$name} }; do? Is this just saying that I want to print a new line for each piece of data within each $name? Thanks.
      it means print each value for the hash referenced at $data{$name} (which would look like this in a data dump (data{APRL} => 7.1963). $_ is a special variable which references the current element. This is the same thing

      foreach my $line (@{$data{$name}}) { #do something }


      Where $line is the same thing as $_, more than 1 way to skin a cat. So it's say print out the hash value of the specified key and also print a new line with it so everything won't be bunched up on a single line. Hope that makes sense.
        OK that makes a lot of sense. One final question. Do you have an idea about how to print each each number (and its respective times) to a different column, using sprintf? Ideally I'd like to read these values into Matlab, and if I could create a column separating each number (1,2...15) with each time, that would save time rather than using Excel. Thanks for all of your help.