in reply to Database Rows into Perl Hash

Never mind, I found how to do it. Just modified the while loop a bit to look like this:

while( my( $comp, $bug_num ) = $sth->fetchrow_array() ) { if (($hash {$comp} eq '') ||($hash {$comp} == '' )) { $hash{ $comp }.=$bug_num; } else { $hash{ $comp}.=",$bug_num"; } }

Is there any other way to do it... specially as the saying goes >> TIMTOWTDI

Replies are listed 'Best First'.
Re^2: Database Rows into Perl Hash
by Athanasius (Archbishop) on Mar 07, 2015 at 12:37 UTC

    Hello vishi,

    Is there any other way to do it...

    Yes! The simplest way is to replace this line in the original:

    $hash{ $comp } = $bug_num;

    with this:

    push @{ $hash{ $comp } }, $bug_num;

    The value corresponding to each hash key is now a reference to an anonymous array containing the bug numbers as its elements.

    Of course, this doesn’t eliminate duplicates. For that, you could use the uniq function (also called distinct) in List::MoreUtils.

    Update: Added quote.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re^2: Database Rows into Perl Hash
by choroba (Cardinal) on Mar 07, 2015 at 12:42 UTC
    $hash {$comp} == ''

    This seems weird. == compares numbers, so it's equivalent to

    $hash{$comp} == 0
    Are you sure you don't want a comma before zero?
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re^2: Database Rows into Perl Hash
by duelafn (Parson) on Mar 07, 2015 at 12:43 UTC

    You could collect the bugs into actual arrays,

    while( my( $comp, $bug_num ) = $sth->fetchrow_array() ) { push @{ $hash {$comp} }, $bug_num; }

    Whether this is better or wors than constructing a string, of course, depends on how you intend to use the data, though even for producing strings I would generally build the arrays (I hate writing code which builds strings / tests whether the string is non-empty) and join with commas at output time: print join ", ", @{ $hash {$comp} };

    Good Day,
        Dean