Trying to convert the following block of perl to python

for($row = 0, $mytype = 500; $row < $filearray_count; $row++) {
                if ($_ eq $filearray[$row][0]) { 
                $mytype = $filearray[$row][1]; 
                print "$row, $mytype,  $_ \n";
                break;

And here is the python attempt. I'm not sure if I'm dealing with $mytype = 500 in the same way

 for member in files:
        for x in range(0, filearray_count):
            mytype = 500
            if member in filearray[x][0]:
                mytype = filearray[x][1]
                #print(x, mytype, member)
                break

Dani AI

Generated

As is translating the loop literally, two small but important language differences should be highlighted. First, Perl's three-part for(init; cond; incr) runs the init portion once before the loop; that means the Perl mytype initializer is executed only once. Second, Perl's eq is string equality, while Python's in tests membership/substring. already pointed out the initializer timing, and correctly flagged the in vs eq issue — both matter for correctness.

A clear, Pythonic translation keeps the initializer outside the loop, uses equality for exact matches, and prefers direct iteration or enumerate when the index is needed. For example, using enumerate yields a compact, readable pattern:

mytype = None
for i, row in enumerate(filearray):
    if member == row[0]:
        mytype = row[1]
        print(i, mytype, member)
        break

For repeated lookups (many members against the same filearray), build a mapping once for O(1) lookup. If duplicates or original indices matter, create a map to (index, value). Example sketch: build {key: (index, value)} and use .get(member); otherwise next(...) with a generator can find the first match without a full scan.

Troubleshooting checklist: confirm filearray_count == len(filearray), ensure row[0] and member are the same types (both strings), avoid in unless substring behavior is desired, and prefer None or a unique object() sentinel instead of arbitrary numeric sentinels like 500. These small adjustments preserve the original logic while making the code safer and more idiomatic.

Recommended Answers

All 5 Replies

Nope. The first part of a 3-statement for clause is run only once, before the first test or the first execution of the loop body. The equivalent would be more like

mytype = 500
for x in range(filearray_count):
    ...

That said, 500 seems to be somewhat arbitrary since you don't use the value of mytype within the loop -- instead, you assign to it before using it.

I would guess that 500 is a sentinel value that is impossible or unlikely to find in the actual filearray structure, and is used after the loop terminates to test whether the inner if statement ever executed. If that's the case, I'd make it a dedicated sentinel instead:

sentinel = False
for x in range(len(filearray)):
    if member in filearray[x][0]:
        sentinel = True
        print(x, filearray[x][1], member, sep=', ')

Notice I also changed range(0, filearray_count) to range(len(filearray)) and changed your print call to use a custom separator so it looks more like the Perl output -- if you need to do more fancy stuff you'd be better off with the str.format method.

If mytype needs to be the last value of filearray[x][1] printed out after the loop terminates, I'd still initialize it to None instead of 500. What's special about 500?

Easier would be just find out what the Perl code is trying to do. I have suspicion that it is overly complicated way to do something easy to do in Python.

One suspicious thing is that you use in in Python when I see eq in Perl.

I think pyTony is probably right. I'm mostly trying to do a direct translation. But I suspect there are many
pythonic improvements that could be made.

I'm rusty on my python chops and I don't know a lick of perl. It's actually a good way to get back into the swing of things.

How come you want to translate the Perl code, when you have no idea of what it does, or do not want to tell it. This is Python forum, I for one can not read Perl for exact meaning of the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.