
griever92
Novice
Oct 30, 2012, 7:23 PM
Views: 5505
|
Using Arguments with Subroutines
|
|
|
I've been running into some issue with one of my scripts now that i've been breaking it into smaller chunks and calling for them using subroutines. Primarily, when it comes to passing arguments from the command line, to the main script, to the subroutine, and then return a value back out into the main script block. I've pulled out the problem area and made a demo set of files to hopefully explain what i'm trying to do. main.pl
#!/usr/bin/perl use strict; use warnings; require '/home/griever92/bin/TESTING_MODEL/testarg/sub.pl'; my $arg = $#ARGV; my $target = ''; print "\n\nArguement is $arg \n"; &callback; print "\n $target \n"; sub.pl
#!/usr/bin/perl use strict; use warnings; sub callback { my $main_arg = @_; my $target = ''; if ($main_arg == -1) { exit 0; } $target = $_[0]; print "\n\n $target \n"; } 1; running this via... perl main.pl this.is.a.test.string produces these results:
Arguement is 0 Use of uninitialized value $target in concatenation (.) or string at /home/griever92/bin/btnup/TESTING_MODEL/testarg/sub.pl line 13. The first print statement is returning a 0, instead of my string, not only that though, the subroutine seemingly receives nothing, and does nothing as well. If I put this same sort of setup into a single file... full.pl
#!/usr/bin/perl use strict; use warnings; my $numArgs = $#ARGV; my $target = ''; if ($numArgs == -1) { exit 0; } foreach $numArgs ($#ARGV) { $target = $ARGV[$numArgs]; } print "\n\n $target \n\n" I receive the following output. Obviously, this is what I want to be seeing returned inside the subroutine for certain operations contained within, as well as being able to use this resultant variable later in the main script block. Unfortunately, I can't seem to get my head around this.
(This post was edited by griever92 on Oct 31, 2012, 5:54 AM)
|