laziness, impatience, and hubris | |
PerlMonks |
Re: Sending Multi file types as e-mail attachmentsby Athanasius (Archbishop) |
on Nov 16, 2015 at 03:36 UTC ( [id://1147771]=note: print w/replies, xml ) | Need Help?? |
Hello merrymonk, I also added the $content_type ‘definition ’ for ms-word and used the ms-excel definition for both .xls and .xlsx files (which did seem to work). I suspect that the code “worked” for the .xlsx file rather by accident than by design. The problem is that the value of $content_type is set correctly only when one of the regex matches succeeds. In the case of files ending in .xlsx and .docx, there is no possible regex match, so $content_type retains whatever value it had in the previous loop iteration. Since the file testx.xlsx happens to follow the file testaaa.xls, $content_type still has the value 'application/vnd.ms-excel'. But when it comes to the file wordtest.docx, the regex tests again all fail and so $content_type still has the value 'application/vnd.ms-excel', which produces a garbled attachment. There are two deficiencies in the code which here combine to produce the problem. First, lexical variables should be declared at the point of first use, to limit their scope as much as possible. By declaring $content_type outside the inner loop, you allow it to retain a spurious value from one iteration to the next. Second, a series of matches should always be terminated by a “no match” clause, handling the case where a match failed to occur. This is good practice even when (as here) it seems as though one of the matches is bound to succeed. So, here is a suggested improvement (untested):
...and then you will need to add code for the cases where the file extension is .xlsx or .docx. (Actually, a better implementation of the above would be to use a hash to associate file extensions with their corresponding content types.) Hope that helps,
In Section
Seekers of Perl Wisdom
|
|