www.webdeveloper.com
Results 1 to 3 of 3

Thread: How can I group lines in a file?

  1. #1
    Join Date
    Mar 2008
    Posts
    32

    How can I group lines in a file?

    Hello all,
    I was wondering, if you have a file like the following:
    Code:
    jim  14
    john 23
    ernest 38
    matilda 43
    jim 34
    ernest 27
    john 44
    matilda 22
    how can you print
    Code:
    jim 14,34
    john 23,44
    ernest 38,27
    matilda 43,22
    I have been trying something with hashes, but didn't get me anywhere...

  2. #2
    Join Date
    Dec 2002
    Location
    Pleasanton, CA
    Posts
    2,132
    Code:
    my %hash;
    while (<DATA>) {
    	my ($name, $number) = split(/\s+/);
    	if (exists $hash{$name}) {
    		$hash{$name} .= ",$number";
    		next;
    	}
    	$hash{$name} = $number;
    }
    for (keys %hash) { print "$_ $hash{$_}\n"; }
    exit;
    
    __DATA__
    jim  14
    john 23
    ernest 38
    matilda 43
    jim 34
    ernest 27
    john 44
    matilda 22

  3. #3
    Join Date
    Dec 2005
    Posts
    2,984
    Haven't done perl in a loooooooong time, but this was fun:

    Code:
    my &#37;namesAges;
    open (MYFILE, "srcfile.txt");
    while(<MYFILE>) {
      ($name,$age) = split(' ',$_);
      if(exists($namesAges{$name})) {
       $namesAges{$name} = $namesAges{$name}.",".$age;
      } else {
       $namesAges{$name} = $age;
      }
    }
    close(MYFILE);

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles