For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > January 2006 > problem passing argument to function









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author problem passing argument to function
Khairul Azmi

2006-01-10, 4:01 am

Hi all,
I have this problem when trying to pass an argument to a function. The
following codes suppose to handle continual characters (the one that end up
with character "\" to indicate a new line). That one works using a solution
I found on the web but the problem is when I tried to pass the argument to a
function declared in the same file, the argument somehow became null. If I
run this program, the print statement does not display anything. Thanks in
advance.

The sample of the input file is as followed
----------------------------------------------------
preprocessor http_inspect_server: server default \
profile all ports { 80 8080 8180 } oversize_dir_length 500 \
cubaan \
test \
ujian

----------------------------------------
#!/usr/bin/perl

sub sample_function {
print "go in $_\n";
}

# get the path for snort.conf file
my $snort_file = $ARGV[0];

if (open (INFILE,"$snort_file")) {
my $index = 0;

while (defined ($line=<INFILE> )) {
chomp($line);
if ($line =~ s/\\$//) {
$line .= <INFILE>;
redo unless eof (INFILE);

}
if ($line !~ /^[[:space:]]*#.*$/) { # handle lines start with #
if ($line =~ /\S/) {
print "$index $line\n";
sample_function($line);
$index++;
}
}
}
close INFILE;
}

Adriano Ferreira

2006-01-10, 4:01 am

On 12/28/05, Khairul Azmi <khairul.azmi@gmail.com> wrote:
> That one works using a solution
> I found on the web but the problem is when I tried to pass the argument t=

o a
> function declared in the same file, the argument somehow became null.


> sub sample_function {
> print "go in $_\n"; <----- $_ is not the first argument, w=

hich is $_[0]
> }


> sample_function($line); <---- when passing the arguments,

the callee will
see @_ =3D ($line)

So you probably fix your code, by doing

sub sample_function {
print "go in $_[0]\n";
}

or

sub sample_function {
my $arg =3D shift; # removes the first element of @_ and returns it
print "go in $arg\n";
}

It is all there in C<perldoc perlsub>.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com