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

Relevant code; $dbh is a DBI database handle and Tr, td are from the CGI module:
foreach (@{$dbh->selectall_arrayref("SELECT * FROM search_atoms WHERE +occurences >= 5 ORDER BY occurences DESC")}) { print Tr( td({'-align' => 'left'}, [ $_->[0 .. 3] ] ) ); }
If it's second argument is an array ref, td is supposed to iterate over it. So there should be four <td>blah</td>'s here as I'm trying to slice the first four elements of the anonymous array that's being extracted out of the selectall_arrayref statement. So basically this is saving me the trouble of writing print Tr( td({'-align' => 'left'}, [ $_->[0],$_->[1],$_->[2],$_->[3] ] ) ); Lazy, am I? Yes. But there error I'm getting is most frustrating; this bit of code causes Perl to segfault every time. Is slicing a referent list verboten? What's the correct way to do this.

Replies are listed 'Best First'.
Re: Slicing a reference?
by Kanji (Parson) on Apr 05, 2002 at 03:31 UTC

    It's not verboten, but it can get ugly. :-)

    What you're looking for is @$_[0..3] which does a slice of $_ after you dereference it.

    On a different note, have you given any thought to explicitly naming the columns you want to return rather than using SELECT *?

    If your schema ever changes, @$_[0..3] might not contain what you think it should, but if you did something like this ...

    my $rows = $dbh->selectall_arrayref(" SELECT foo, bar, baz, quux FROM search_atoms WHERE occurences >= 5 ORDER BY occurences DESC "); foreach ( @$rows ) { print Tr( td( {'-align' => 'left'}, $_ ) ); }

    ... each row would only contain what you need and expect, along with the pleasant side effect of not needing to slice up a reference.

        --k.


(crazyinsomniac) Re: Slicing a reference?
by crazyinsomniac (Prior) on Apr 05, 2002 at 03:27 UTC
Re: Slicing a reference?
by shotgunefx (Parson) on Apr 05, 2002 at 03:35 UTC
    Well as far as the reference, this should work.

    [@{$_}[0..3]]


    -Lee

    "To be civilized is to deny one's nature."
(tye)Re: Slicing a reference?
by tye (Sage) on Apr 05, 2002 at 23:38 UTC