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

Hi all, Little lost with this problem. I have an input file similar to
18 56 25 10 12 45
First Column is called PDB second PIC. If i have a sumber stored in $NUM17 = 25. I need to make sure that $NUM17 appears in column one then print its corresponding PIC, column 2 number. I thought something along:
while (<DATA>) { ($PDB, $PIC) = split (/\s+/, $_) if (/^\d+.*/); } @pic = $PIC; @pdb = $PDB; $endpdb = scalar @pdb; for ($count = 0; $count < $endpdb; count++;) { if ($PDB == $NUM17) {$value = $pic[$count]}; }
thanks, #print "$value\n";

Replies are listed 'Best First'.
Re: Working with Arrays
by davorg (Chancellor) on Jul 07, 2004 at 12:25 UTC

    Why make it so complex :)

    while (<DATA>) { print +(split)[1], "\n" if /^$NUM17\b/; }
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      thanks Dave this will do the job!
Re: Working with Arrays
by naChoZ (Curate) on Jul 07, 2004 at 12:06 UTC

    This smacks of homework, but...

    I think in this case you probably want a hash, not an array, assuming PIC will not have duplicates.

    my %foo = ( 18 => 56, 25 => 10, 12 => 45, .. ); print $foo{ 18 };

    --
    Diplomacy is the art of saying "Nice doggie" until you can find a rock.
    naChoZ

      not homework just trying to learn and apply perl, beyond the stage of homework problem is that this is not suitbable, as the file could be 1000 lines long
        this is not suitbable, as the file could be 1000 lines long

        1000 lines is not all that long. This should be plenty small enough to load into memory, as long as you're not on a very limited system. As a test, you can try loading up hashes with different numbers of elements, and looking to see what the memory usage is:

        perl -e 'my %hash = map {$_=>$_} 1 .. 1_000; print "done"; sleep' perl -e 'my %hash = map {$_=>$_} 1 .. 10_000; print "done"; sleep' perl -e 'my %hash = map {$_=>$_} 1 .. 100_000; print "done"; sleep'

        On my system, the version that loaded 100,000 numbers used 21mb of memory. The version that loaded 1,000 numbers only used 3mb. On any modern computer, this should be a reasonable amount.

Re: Working with Arrays
by naChoZ (Curate) on Jul 07, 2004 at 12:17 UTC

    Populate the hash in your while loop.

    my %foo; while (<DATA>) { .. $foo{ $PIC } = $PDB; }

    --
    Diplomacy is the art of saying "Nice doggie" until you can find a rock.
    naChoZ