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

Ave fellow monks,

From the frightening depths of ignorance I come for thee again, to ask for thy infinite wisdom.

I have the following construction (extract):

opendir(DIR, "$dirstr") || die ("[error] proc [...]"); rewinddir (DIR); @piclist = grep(!/^\.\.?$/ && /.jpg$/, readdir (DIR)); closedir (DIR); $index = grep $piclist[$_] eq $pic, 0 .. $#piclist; print "$index\n"; print "$piclist[$index] equals $pic\n";

It opens a directory, searches for a certain file in the list, and returns the index of that file (so I can link to previous and next picture in a gallery). The problem is that index is always '1', and the second print-out says 'SininenLaguuni.jpg equals KeltaisenKesanBooli.jpg', which is clearly not the case.

If I do the index-searching like this:

my ($c); foreach $c (0 .. $#piclist) { print "$c - $piclist[$c] equals $pic\n" if ($piclist[$c] eq $pic); }

... it seems to work: '9 - KeltaisenKesanBooli.jpg equals KeltaisenKesanBooli.jpg'.

What I don't understand is why the first solution doesn't and the second one does work. These are all list operations on lists, as far as I see.

Enlighten me, please... I'm sure it's something very stupid I'm too tired to see.


thanks,

   wouter

Replies are listed 'Best First'.
Re: not a list?
by Kanji (Parson) on Jul 26, 2002 at 02:10 UTC

    An absence of parens is changing your context, so you're seeing the number of matches, rather than the match(es) themselves.

    ($index) = grep $piclist[$_] eq $pic, 0 .. $#piclist;

        --k.


      Doh... you're right. Thanks. ;)
Re: not a list?
by dws (Chancellor) on Jul 26, 2002 at 03:56 UTC
    There's something fundamentally strange with what you're doing. To associate a file with a directory index is a risky thing to do, since file ordering in directories isn't portable across types of file systems. In general, you can't assume a directory "position" for a file unless the directory is static. Even then, that's risky.

    What is it that you're doing that requires a directory "index"?

      I know what you mean, but I don't think there's a problem it this case. I want to be able to provide links to the previous and next pictures starting from a certain 'current' picture in a photo gallery. The idea is that when someone clicks on a thumbnail, they can choose prev/next to move through the pictures without returning to the thumbnails.

      Most unix systems give the files by default in order they were created or by the sequence of links in fats, I think. The exact position isn't so important, as long as it's consistent within the html session. Which it should be, unless files are updated or moved while somebody is watching them.

      I could sort them alphabetically or so, but I don't really see the point of doing that. It's really not that important.