Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

problem ..related to perl package concept

by perlplayer (Sexton)
on Dec 09, 2008 at 04:31 UTC ( [id://729076]=perlquestion: print w/replies, xml ) Need Help??

perlplayer has asked for the wisdom of the Perl Monks concerning the following question:

i am writing a script like this
#! /usr/bin/perl $var='one'; mypackage::var='two'; sub mypackage::func(){ print "my \$var is $var"; } mypackage:: func();
i want to print the value from my package but not from main but it is not working can anyone explain why ... i have seen in perlmod that we define a sub in a different package if we explicitly declare its name with the package we intend to keep it in. OUTPUT

csbu061 mhalder 125: perl test2.pl Can't modify constant item in scalar assignment at test2.pl line 6, near "'two';" Execution of test2.pl aborted due to compilation errors.

Replies are listed 'Best First'.
Re: problem ..related to perl package concept
by moritz (Cardinal) on Dec 09, 2008 at 07:44 UTC
    can anyone explain why

    You're putting a sub into a different package, but you're not in that package. If you want that, use something like this:

    #!/usr/bin/perl -w $var='one'; $mypackage::var='two'; { package mypackage; sub func { print "my \$var is $var\n"; } } mypackage::func(); __END__ Name "main::var" used only once: possible typo at foo.pl line 3. my $var is two
Re: problem ..related to perl package concept
by Bloodnok (Vicar) on Dec 09, 2008 at 09:07 UTC
    Errrm, if you'd used strictures, they might just have spotted that mypackage::var='two'; is in error - you forgot to prefix the var name with the var type e.g. $mypackage::var='two';...

    A user level that continues to overstate my experience :-))
Re: problem ..related to perl package concept
by jasonk (Parson) on Dec 09, 2008 at 04:36 UTC

    It doesn't really have anything to do with packages, it comes down to the difference between $var and var. You need a $ on the second one too...


    www.jasonkohles.com
    We're not surrounded, we're in a target-rich environment!
Re: problem ..related to perl package concept
by kyle (Abbot) on Dec 09, 2008 at 15:51 UTC

    You don't need to put the sub in the other package in order to access that package's variables. Just refer to them explicitly, as you do in the assignment.

    $var = 'one'; $mypackage::var = 'two'; sub we_got_the_func { print "Other \$var is $mypackage::var\n"; } we_got_the_func(); __END__ Other $var is 'two'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://729076]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-04-19 00:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found