in reply to Searching for two lines that begin with the same string

You want a hash indexed by the token you want to match. You might as well store the complete lines as the hash value. Then output the values which have more than one entry. (Untested) code:
my %routes; while (my $line = <>) { # Grab the route my ($key) = ($line =~ /^(\S+)\s/); # Make sure we have an array ref for this key $route{$key} ||= []; # And add this line push @{$route{$key}}, $line; } foreach my $value (values %routes) { if (@$values > 1) { print @$values; print "\n"; } }
Something like that anyway.

Replies are listed 'Best First'.
Re^2: Searching for two lines that begin with the same string
by johngg (Canon) on Dec 18, 2006 at 16:54 UTC
    You don't have to make sure of having an array ref. for a particular key, your code $route{$key} ||= [];, as doing the push @{$route{$key}}, $line; will push onto an auto-vivified array ref. if one doesn't exist or push onto the existing ref. otherwise.

    Cheers,

    JohnGG

      Thanks very much. I didn't know that push would auto-vivify in that way. That's going to reduce my line count a bit more in the future.
Re^2: Searching for two lines that begin with the same string
by tgrossner (Novice) on Dec 18, 2006 at 16:53 UTC
    How are you populating $line from the file? I have tried opening the file then going into the while loop, but it doesnt seem to be reading the lines into the while loop.

      We used <>, which reads from the files named on the command line, or STDIN if none were specified on the command line. You could read from any other file handles instead just by specifying it.

      open(my $data_fh, '<', $data_file_name) or die("Unable to open data file \"$data_file_name\": $!\n"); while (my $line = <$data_fh>) { . . .

      You should replace the word "data" with something more descriptive, at least in the error message.