Re: simple hash

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

  N> Why is this code not working?

a probable cause is below as well as some code review

  N> #!/usr/bin/perl -w
  N> use strict;
  N> use warnings;

don't put -w and use warnings in. they basically do the same thing and
use warnings is better.

  N> my %years;
  N> while (<DATA>) {

don't use $_ as much as you do. use a named variable as it helps make
the code easier to understan.

  N> chomp;

ever heard of indenting or formatting your code? if you need help, look
for perltidy which can do it for you.

  N> my $year = (split /\t/)[3];

you are splitting on tabs. do you really know the data has tabs in it?
the data you pasted here seems to have spaces. now that could have
happened in pasting your data into your newsreader but it could be from
before. assuming spaces will force the split to return only 1 element as
it finds no tabs. indexing for the 4th element will get undef which is
what you are seeing.

also don't name a scalar and hash with such similar names. the hash
would be better named %year_cnt or something like that.

  N> $years++;
  N> }
  N> foreach (sort keys %years) {

again, use a named variable here instead of $_

  N> print "In $_, $years CDs were released.\n";
  N> }

  N> __DATA__
  N> Bragg, Billy**Workers' Playtime**Cooking Vinyl**1987

those *'s are where you think tabs would be but they are spaces
here. check the actual data source or how you put it into DATA.


Uri Guttman  ------  -------- --
-----  Perl Code Review , Architecture, Development, Training, Support ------
---------  Gourmet Hot Cocoa Mix  ---- ---------

Re: simple hash

Quoted text here. Click to load it

I do this all the time.  Once you get the hang of it, it makes naming stuff
a lot easier.  Agreed it may confuse things a bit,


Site Timeline