don't call SvPV and toss the result if no PerlIO ptr

If f is NULL, SvPV and Perl_get_context are unnecessarily executed. Fix
it for efficiency. Move 2nd dTHX to the scope where it is first used
similar to commit 2bcd6579c4 .