in reply to Re-ordering items by $id from a flat file
You appear to be modifying a database file without any file locking. Bad.
I'm not sure what all your code is meant to do, but I think you could do better with Tie::File or with a simpler way of handling data. You appear to be swapping adjacent pairs of elements according to the values in some magic variables with no apparent origin. As single variables, that seems to mean that you are only swapping one time in all that.
Lets recognise that an instruction to "moveup" for element n is an instruction to "movedown" for element n-1. That is a more convenient representation for the assumption that the moves will be done You can read a flat file of records into an array, and then replace the elements with a hashref, [Struck, not used in code] or just say,
The tied interface writes changes to the file as you make tham. @menuitems is untied at the end to flush writes before losing the lock.use Fcntl ':flock'; use Tie::File; sub reordermenu { # set $info{'m_id'), $m_action somehow # from parameters passed to this. Think # of a better data structure. my $df = tie my @menuitems, 'Tie::File', "$datadir/defaults/menu.dat"; $df->flock(O_EXCL); my @indexes = grep { $info{'m_id'} eq (split /\|/, @menuitems[$_], 2)[0] } 0 .. $#menuitems; for (@indexes) { my $tondx = $m_action eq 'moveup' ? $_ ? $_-1 : $_ : $_ == $#menuitems ? $_+1 : $_; @menuitems[$_, $tondx] = @menuitems[$tondx, $_]; } untie @menuitems; 1; }
I've omitted a lot of extra stuff because I don't know what it does. Some looks suspicious, like that exit at the seemingly normal end of the sub. That can't be right.
After Compline,
Zaxo
|
|---|