views:

44

answers:

2

I have one script i'm trying to call from another script, passing the information from the script that is being called to the calling script. When i use do or require it runs through but doesnt pass the value.

ex.

I have the following line at the bottom of the script that i am calling

called script.pl

print " $hold IS VALUE\n";

which prints me the value of hold.

I then start the calling script with:

calling_script.pl

require 'acc_option.pl'; print "HOLD PASSED IS $hold\n";

but the variable hold doesnt print.

Whats the best way to call this script instead of putting everything on one long ass page?

+2  A: 

You have started down the right path, but are still a ways off. You should be using modules and the use statment, not code and the require statement. You should try reading perldoc perlmod and perldoc perlmodlib, but the general gist is:

  1. decompose your process into functions
  2. group those functions by what they do
  3. put the groups of functions into modules
  4. write a script that uses the modules and calls the functions

Think of the script as a skeleton and the functions as fleshing out the skeleton.

Here is a simple module and a script that uses it:

ExampleModule.pm:

package ExampleModule;

use strict;
use warnings;

use base 'Exporter';

our @EXPORT_OK  = qw/do_first_thing do_second_thing do_third_thing/;

sub do_first_thing {
    my ($thing) = @_;

    return $thing + 1;
}

sub do_second_thing {
    my ($thing) = @_;

    return $thing + 1;
}

sub do_third_thing {
    my ($thing) = @_;

    return $thing + 1;
}

1;

example.pl:

#!/usr/bin/perl

use strict;
use warnings;

use ExampleModule qw/do_first_thing do_second_thing do_third_thing/;

my $thing = 0;

$thing = do_first_thing($thing);
$thing = do_second_thing($thing);
$thing = do_third_thing($thing);

print "$thing\n";
Chas. Owens
+2  A: 

It depends on how $hold was declared.

If it was lexically declared (with "my $hold...") then you can't get at it directly - it's only accessible within the scope of called_script.pl.

If it's dynamically scoped (local $hold, or our $hold) then you should be able to get at it by prefixing it with the package it was declared under (so if it's in "package Foo;" you can get at it as $Foo::hold").

That said...

You generally don't want to mess around passing variables between scripts. Storing state in global variables can make for some nasty debugging sessions.

As a first step you might want to encapsulate accessing $hold inside a subroutine so in called_script.pl you have something like:

sub is_on_hold { return $hold };

which will return $hold when called (I'm assuming here that $hold is some kind of boolean state indicator. If it isn't name your subroutine in an appropriately intention revealing way :-)

If you describe how you're trying to use $hold in a bit more detail folk might be able to give some more specific advice on a better way of doing your task.

adrianh