First ... Back ... Next ... Last ... (Notes home)

Use and Require

Adding Functionality to the Perl Baseline

  • The Perl interpreter needs to load information about many different things at startup. Therefore, it doesn't load every possible thing, but takes cues from the programmer about what is needed.
  • The use of Perl's use and require are similar to Java's import or C/C++'s include statements.
  • use loads in modules at compile time, while require waits until run time. Thus, use is usually prefered.
  • The @INC array specifies the search path to employ when looking for add-in modules. This will include your current directory.
  • Quick use vs. require example
    use.pl:
    
    #!/usr/bin/perl -w
    
    # This loads in a module called "strict":
    #use strict;
    
    # This loads in a module called "use-in"
    use using;
    
    # This loads in a file (which might not be a module) called "using.pl"
    require "using.pl";
    
    print $blah::test . ", ";
    print $test . "\n";
    
    --
    using.pm:
    # .pm packages are loaded at compile time, so should not include
    # interactive content
    package blah;
    our $test="hi there";
    return 1;
    
    --
    using.pl:
    # Import via "require" happens at run-time, so we can include
    # interactive items:
    print "Welcome to using.pl\n";
    our $test="big guy";
    
  • We'll have more about using and creating modules in future classes.
  • For now: consider putting shared functionality in a separate file that you can re-use for many different programs. This works very well for your own subroutines.

First ... Back ... Next ... Last ... (Notes home)

UAF Computer Science
Prof. Greg Newby