- sv_unmagic(sv, PERL_MAGIC_backref);
- if (SvTYPE(sv) != SVt_PVCV)
- mg_free(sv);
- }
+ /* if a my variable that was made readonly is
+ * going out of scope, we want to remove the
+ * readonlyness so that it can go out of scope
+ * quietly
+ */
+ if (SvREADONLY(sv) && !SvFAKE(sv))
+ SvREADONLY_off(sv);
+
+ if (SvOOK(sv)) { /* OOK or HvAUX */
+ if (SvTYPE(sv) == SVt_PVHV)
+ Perl_hv_kill_backrefs(aTHX_ MUTABLE_HV(sv));
+ else
+ sv_backoff(sv);
+ }
+
+ if (SvMAGICAL(sv)) {
+ /* note that backrefs (either in HvAUX or magic)
+ * must be removed before other magic */
+ sv_unmagic(sv, PERL_MAGIC_backref);
+ if (SvTYPE(sv) != SVt_PVCV)
+ mg_free(sv);
+ }
+ if (SvTHINKFIRST(sv))
+ sv_force_normal_flags(sv, SV_IMMEDIATE_UNREF
+ |SV_COW_DROP_PV);