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

Greetings, I am a newbie, so please bear with me if this is too simple to be posted. When I run the following code, I don't get any output. I have included the expected output at the bottom. What am I missing? I could directly "print $version", but I need to access through a hash(key) for additional processing. Using Perl version 5.8.8

use strict ; my %seen = (); while(<DATA>){ chomp; my($file,$version) = split(/vobx/,$_); print "$seen{$file} \n"; } __DATA__ /view/d602_edf3/vobx/copy/pp/copy/ticrwpth /view/d602_edf3/vobx/copy/pp/copy/ticrwptr /view/d602_edf3/vobx/copy/pp/copy/tirrwphz /view/d602_edf3/vobx/copy/pp/copy/tirrwprq

Expected output : /copy/pp/copy/ticrwpth /copy/pp/copy/ticrwptr /copy/pp/copy/tirrwphz /copy/pp/copy/tirrwprq

I understand I can get the string I need from the $version. But like I mentioned, I need to be able to access it as a $hash{$key}. I am not sure why this code is not working.

Here is what I am actually trying to do. Assume that, I have a file which looks as follows file1@@/main/trunk/1 file2@@/main/trunk/2 file2@@/main/trunk/3 file1@@/main/trunk/2 file1@@/main/trunk_2/1 If the file name (before @@) is unique, I need to capture that straight away. If there is trunk_2, that line trumps other lines which have the same file name. If there is no trunk_2, I need to get the line with just "trunk" which has the highest numeric at the end after the last "/". There might be more than one line for trunk_2 with different numeric at the end, in which case, I need to get the higher numeric among all lines with same file names before "@@". So, the output should be file1@@/main/trunk_2/1 file2@@/main/trunk/3 Hope this helps.

Replies are listed 'Best First'.
Re: Split and hash
by almut (Canon) on Dec 22, 2009 at 21:41 UTC

    You haven't assigned anything to %seen.

    Maybe add

    $seen{$file} = $version;

    before the print statement.   Or even

    push @{ $seen{$file} }, $version; print "@{$seen{$file}} \n";

    as the $file part (hash key) seems to be the same in all cases (at least for the sample data).  The latter would create an array for a hash entry/key "/view/d602_edf3/" with the array holding all values of $version...

    Maybe you could elaborate on what exactly you're trying to achieve.

Re: Split and hash
by ikegami (Patriarch) on Dec 22, 2009 at 21:36 UTC

    You get four warnings and four blank lines for output because %seen doesn't contains anything. The text you want to is in $version. If you want it in %seen, put it in %seen.