PDA

View Full Version : paramerters in perl & an input problem


Apodysophilia
12-22-2003, 01:45 AM
i just dont get it bah.
this works, i found a tut on it
#!/usr/bin/perl


sub test
{
$temp = $_ for @_;
print "the var is $temp";
}

test(34);


i dont knwo what the "$_ for @_ " does? and that only works for one argument. what if i want more?
and that doesnt work for text, how do i do it for text?

sub test
{
$temp = shift(@_) ;
print "the add is $temp";
}

test(23);

what does the shift() do. and why does it have to be an array?

i am just more confused now:wtf:

also

@info = <STDIN>;
how do i terminate this. or/and is there a better way to get input from the keyboard?


$temp = <> ;
also works for input, so what does STDIN stand/used for?


thanks for you time


:wavey:

little birdy
12-23-2003, 02:19 AM
ok, i'll try to break this stuff up for ya.

i) $_ and @_ are special variables. @_ is a special array that holds any arguments passed to a subroutine, and $_ is a default scalar variable. in the case of something like this loop: "foreach (@_) { ...}", the program would loop through the array. each iteration, the next element from the array is put into the default variable, $_, so you can work with it. that one line for loop just assigns each element in @_ to $temp (so when all is said and done, $temp will be the same as the last element in @_)

ii) shift() removes the first item from an array (and, of course, that's why it needs to be given an array! :p). conversely, unshift() adds an item to the beginning of an array. (and pop() removes the last item in an array, and push() adds an item to the end of an array). for more information on these built-in functions -- and all kinds of other things -- visit http://www.perldoc.com/ because it's the best source of perl information you're going to find, i think.

iii) standard input is used a little differently, in the case of perl/CGI programming. a CGI program must have all of the data it requires before it is run; you cannot "prompt" for data while a perl/CGI program is running, necessarily (at least, not with standard input). in CGI programming, standard input is used to relay form data from CGI to your perl program, when you have HTML forms using the POST method. (the GET method uses the environment variable QUERY_STRING - $ENV{'QUERY_STRING'} - to pass along it's form data).

i hope this makes things a little clearer? :)

[edit: one more note - when you are getting form data from either STDIN or the QUERY_STRING, you must parse the data, because as you might have notice, certain characters are replaced by special codes. for example, a space (' ') is replaced by '%20". fortunately, the CGI module -- something else for you to look up in the perldoc -- does all of the parsing for you.]