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

Hello,

If I know the name of one element ( for example Element_15 in a table (but not its place), is there a simple function to get the element whose place is just before Element_15 ?

Thanks a lot

Replies are listed 'Best First'.
Re: how to find an element in a table
by pc88mxer (Vicar) on Feb 15, 2008 at 18:03 UTC
    It all depends on how you are implementing your "table." If it is an array, you could do something like this:

    # assume @a is your array my $pos; for my $i (0..$#a) { if ($a[$i] eq "Element_15") { $pos = $i; last; } }

    $pos is either undef or the position of the first occurrence of "Element_15".

    Hashes don't have any defined order to them, so the question doesn't make any sense if you are using a hash. If your "table" is an HTML table, that's a completely different situation.

Re: how to find an element in a table
by Jenda (Abbot) on Feb 15, 2008 at 18:50 UTC

    If you happened to mean a database table then you first have to define the order, then get the value of the order column(s) for that row and then select one row that would be before that row in the ordering.

    Assuming the table is named People, you want it sorted on LastName and then FirstName and want the person just before the person with ID 15 it could be something like this:

    SELECT TOP 1 Previous.* from People as Previous join People as This on Previous.LastName < This.LastName or Previous +.LastName = This.LastName and Previous.FirstName < This.FirstName WHERE This.ID = 15 ORDER BY Previous.LastName DESC, Previous.FirstName DESC
    If you happened to be looking for the guy just before John Doe it would be simpler:
    SELECT TOP 1 * from People WHERE LastName < 'Doe' or LastName = 'Doe' and FirstName < 'Joe' ORDER BY Previous.LastName DESC, Previous.FirstName DESC

Re: how to find an element in a table
by Fletch (Bishop) on Feb 15, 2008 at 17:06 UTC
Re: how to find an element in a table
by misterwhipple (Monk) on Feb 15, 2008 at 17:18 UTC
    When you say "table", it looks like you mean "hash", right? The order of elements in a hash is not fixed except as an (unreliable) side effect.

    This recipe for implementing sparse arrays using hashes might help with what you want.

    On the other hand, if the Element_<number>s are all consecutive, you might be better off ditching hashes altogether and using a plain array. The previous-element problem becomes trivial, though searching an array for a known value is less simple.

    cat >~/.sig </dev/interesting