Kafkas has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I have a data.txt list with informations about students. Each line with informations about:
name,id_number,faculty,exam day(in form of "yyyy/mm/dd"),address,...

I want to understand how the programm works.Who can tell me, how the hash in line 9 will be created and how it works with $hash{year}(line 13)?

Thanks for any answer
(and excues me for my worse English)

1 #!/usr/bin/perl -w 2 3 my $filename = "data.txt" ; 4 my %hash=(); 5 6 open(FILEHANDLE,"<$filename") || die "Cannot open $filename!"; 7 while(my $line=){ 8 chomp $line; 9 $hash{$1}++ if ($line =~ /.*:(.{4})\/.{2}\/.{2}:.*$/); 10 } 11 close(FILEHANDLE); 12 13 print "In the Year 2002 you checked $hash{ 2002 } exams! \n";

20040315 Edit by Corion: Added code tags

Replies are listed 'Best First'.
Re: Beginner question hash&RegEx
by Abigail-II (Bishop) on Mar 15, 2004 at 11:51 UTC
    $hash{$1}++ if ($line =~ /.*:(.{4})\/.{2}\/.{2}:.*$/)
    First, $line (the current line) is matched against the regex /.*:(.{4})\/.{2}\/.{2}:.*$/, which looks for a colon, 4 characters, a slash, 2 characters, another slash, 2 characters, and a colon. If there is a match, the set of 4 characters is remembered in $1, and that value is used to increment the associated value in the hash.

    For instance, if the current line is foo,bar,baz:2002/12/12:feeble it captures the 2002, and increments $hash{2002} with one.

    print "In the Year 2002 you checked $hash{ 2002 } exams! \n";
    This is just a simple print statement, interpolating the value $hash{2002}.

    Abigail

Re: Beginner question hash&RegEx
by astroboy (Chaplain) on Mar 15, 2004 at 11:59 UTC

    Hmm, this seems a bit dodgy, but you have a regular expression that basically looking for anything, followed by a colon followed by any 4 characters followed by "/" followed by two characters followed by "/" followed by 2 characters, followed by a colon, followed by anything. If there is a match then the four characters will be assigned to $1.

    As $1 is the hash index, then whenever 2002 is encountered then the value for key 2002 is incremented

    However, I should point out that the regular expression doesn't distinguish between alpha characters and digits, that the date could be in the wrong field, and probably many more issues that other monks may point out.

    P.S. Is this homework?

Re: Beginner question hash&RegEx
by Kafkas (Initiate) on Mar 15, 2004 at 13:00 UTC
    Thnaks for your answers, it's the answer from a student in an exam. I try to understand what he makes...
    now with your help, I know what happens in this prog,thanks.