CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
how can I pass ARGV

 



digioleg54
User

Mar 1, 2017, 2:37 PM

Post #1 of 3 (1241 views)
how can I pass ARGV Can't Post

If I pass @ARGV, like arg1 usr/passwd/host/port date, is it possible to use it like this:
my $db_conn = shift @ARGV;
my ($user_id,$passwd,$srv,$prt) = shift @ARGV;
Or I have to put @ARGV to one variable and split it to others?
Can I use ARGV in sub?


Laurent_R
Veteran / Moderator

Mar 2, 2017, 5:39 AM

Post #2 of 3 (1235 views)
Re: [digioleg54] how can I pass ARGV [In reply to] Can't Post


In Reply To
If I pass @ARGV, like arg1 usr/passwd/host/port date, is it possible to use it like this:
my $db_conn = shift @ARGV;


Yes you can do that, this will assign the first item of @ARGV to $db_conn and remove it from @ARGV.


In Reply To
my ($user_id,$passwd,$srv,$prt) = shift @ARGV;


That's not correct, because shift @ARGV; will return only one item, so that only $user_id will be populated.

But you can make a list assignment:


Code
my ($user_id,$passwd,$srv,$prt) = @ARGV;



In Reply To
Or I have to put @ARGV to one variable and split it to others?
Can I use ARGV in sub?

You can always copy @ARGV into another array, if that's what you mean, but I doubt you need it.

And yes, you can use @ARGV in a sub if you wish. For example in this one-liner:


Code
$ perl -e ' a(); sub a { print "@ARGV\n" } ' foo bar 
foo bar



(This post was edited by Laurent_R on Mar 2, 2017, 5:40 AM)


BillKSmith
Veteran

Mar 2, 2017, 7:34 AM

Post #3 of 3 (1228 views)
Re: [digioleg54] how can I pass ARGV [In reply to] Can't Post

The explanation for all of Laurent's answers is that @ARGV is a Perl variable. It is special in only three ways. (Refer to paragraph "The Syntax of Variable Names" in perldoc perlvar)

  • It is exempt from strict 'vars'

  • It is always created in package 'main'

  • It always refers to @main::ARGV (even when the reference is in the scope of another package)


  • None of these apply to your example. Because you did not use 'strict', all your undeclared variables are package variables. Because you did not use 'package', all your code and its variables are in the default package 'main'.

    In other words, Laurent's syntax would apply to any array not just @ARGV.
    Good Luck,
    Bill

     
     


    Search for (options) Powered by Gossamer Forum v.1.2.0

    Web Applications & Managed Hosting Powered by Gossamer Threads
    Visit our Mailing List Archives