in reply to Perl beginner's issue with hash

The reason of the weird result is the setting of this inconspicuous variable:
$/ = undef;

It enables the "slurp mode", i.e. <FILE> reads the whole file into $_. But you then check

if (/$i/g)
which only runs once.

You can fix it in several ways:

  1. keep the $/ unchanged. It will read the file line by line and update the variable appropriately.
  2. replace the if by while, it will run the increment for each match
  3. create a regex from all the ids and match all of them at once:
    my $regex = join '|', map quotemeta, @ids; while (<FILE>) { $counts{$1}++ if /($regex)/; }

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Perl beginner's issue with hash
by Maire (Scribe) on Apr 23, 2020 at 11:50 UTC
    Thanks so much for this! Just as a quick follow-up, do you have any thoughts why I might be receiving an error when I change the 'if' to a 'while' statement? All I've changed is the 'if' for a 'while', but then the following appears when I try to run:
    syntax error at step_two_redux.pl line 19, near "else" syntax error step_two_redux.pl line 28, near "}" Execution of step_two_redux.pl aborted due to compilation errors.
      All I've changed is the 'if' for a 'while' ...

      If all you've done is change
          if (CONDITION) { ... } else { ... }
      to
          while (CONDITION) { ... } else { ... }
      then yes, this is a syntax error because there is no  while ... else ... statement block structure in Perl. (The only  if statement | statement block I can see in the OPed code is  if (/$id/g) { ... } — is this the one you're referring to?)

      I'm not sure what you were trying to accomplish with this change, so I'm not sure what to advise as the proper change.


      Give a man a fish:  <%-{-{-{-<