<?xml version="1.0" encoding="windows-1252"?>
<node id="1004533" title="Re: Moose and File::Temp" created="2012-11-19 08:19:55" updated="2012-11-19 08:19:55">
<type id="11">
note</type>
<author id="757127">
tobyink</author>
<data>
<field name="doctext">
&lt;p&gt;The two answers above should address the problem you're having. Here are some style tips though...&lt;/p&gt;

&lt;p&gt;In these two lines, you are treating &lt;c&gt;$self&lt;/c&gt; like it is a hashref...&lt;/p&gt;

&lt;code&gt;
$self-&gt;{tempfile} = File::Temp-&gt;new(UNLINK =&gt; 1, SUFFIX =&gt; '.tmp');
print $self-&gt;{tempfile} "I am here";
&lt;/code&gt;

&lt;p&gt;But self is not a hashref; it's an object. OK, so Moose implements objects as blessed hashrefs by default, but it is considered bad form to treat an object as a hashref - we're supposed to pretend that it's not a hashref, and only access the internals via the accessors that Moose gives us. So we should do this...&lt;/p&gt;

&lt;code&gt;
$self-&gt;tempfile( File::Temp-&gt;new(UNLINK =&gt; 1, SUFFIX =&gt; '.tmp') );
print {$self-&gt;tempfile} "I am here";
&lt;/code&gt;

&lt;p&gt;The reasons for doing so are not just theoretical. Accessing the object as a hashref bypasses all your type constraints, triggers, etc.&lt;/p&gt;

&lt;p&gt;Secondly, you are initialising an attribute within the &lt;c&gt;BUILD&lt;/c&gt; method. While you &lt;em&gt;can&lt;/em&gt; do that, Moose does provide attribute defaults and builders for this sort of thing:&lt;/p&gt;

&lt;code&gt;
package test;   # not 'test.pm'
use Moose;
use File::Temp;

has tempfile =&gt; (
    is       =&gt; 'rw',
    isa      =&gt; 'File::Temp',
    lazy     =&gt; 1,
    default  =&gt; sub {
        File::Temp-&gt;new(UNLINK =&gt; 1, SUFFIX =&gt; '.tmp')
    },
);

sub BUILD {
    my $self = shift;
    print { $self-&gt;tempfile } "I am here";
}
&lt;/code&gt;

&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-757127"&gt;
&lt;small&gt;&lt;small&gt;
&lt;tt&gt;perl -E'sub Monkey::do{say$_,for@_,do{($monkey=&amp;#x5B;caller(0)]-&gt;&amp;#x5B;3])=~s{::}{ }and$monkey}}"Monkey say"-&gt;Monkey::do'
&lt;/tt&gt;&lt;/small&gt;&lt;/small&gt;
&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
1004523</field>
<field name="parent_node">
1004523</field>
</data>
</node>
