perl - How can I modify a scalar reference passed to a subroutine reference? -


I have a function to convert documents into different formats, which then calls another function based on type document is. It is very easy for everything different from HTML documents, which requires cleaning, and it is clear that where it comes from is based on. So I had the idea that I could cross the context of a sub-routine in the Convert function, so that the caller gets an opportunity to modify the HTML, only a few (I'm not working, so copy and paste it ):

  package converter; ... Sub changed {my ($ self, $ filename, $ coderef) = @_; If ($ filename = ~ / html? $ / I) {$ self- & gt; _convert_html ($ filename, $ coderef); }} Sub_convert_html {my ($ self, $ filename, $ coderef) = @_; My $ html = $ self- & gt; Slurp ($ filename); $ Coderef-> (\ $ HTML); #this html $ self- & gt; Modifies save_to_file ($ filename, $ html); }  

then called:

  converter-> New- & gt; Convert ("./ whatever.html", sub {s / & lt; html & gt; / & lt; xml & gt; / i});  

I have tried some different things with these lines, but I continue using 'unused value in the replacement (S ///)'. Is there a way to do that I am trying to do?

Thanks

If it were mine, I avoid modifying scalar referee Will go and just replace the value:

  sub_convert_html {my ($ self, $ filename, $ coderef) = @_; My $ html = $ self- & gt; Slurp ($ filename); $ Html = $ coderef-> ($ Html); #this html $ self- & gt; Modifies save_to_file ($ filename, $ html); }  

However, if you want to modify the arguments of each one, then it is necessary to know that all sub logic pass-by references in Perl ( @_ Sub-call arguments are aliased). So your conversion may look like sub:

  sub {; Html & gt; $ _ [0] = ~ s / & lt / & lt; Xml & gt; /}>  

But if you really want to work on $ _ , as if you were in your desired code example, you would have to go to _convert_html ( ) should look like:

  sub_convert_html {my ($ self, $ filename, $ coderef) = @_; My $ html = $ self- & gt; Slurp ($ filename); $ Coderef-> () For $ html; $ Self- & gt; Saving_t_file ($ filename, $ html); }  

for is an easy way to properly localize $ _ . You can also:

  sub_convert_html {my ($ self, $ filename, $ coderef) = @_; Local $ _ = $ Self- & gt; Slurp ($ filename); $ Coderef-> (); $ Self- & gt; Saving_t_file ($ filename, $ _); }  

Comments