How to give an array to a function ? Whats wrong

P

pod69

Hello
I am a little bit confused now ? Whats wrong here?

#!/usr/bin/perl

my @bla = ("sdf","sdf","sdf");
print scalar(@bla);
create(@bla);


sub create{
my @arg = shift;
print scalar(@arg);
foreach my $b(@arg){
print "yes";
}
}


In the function the array conists of one element but where are the
other two?
How can I give a function the whole array?

thx
 
B

Ben Morrow

Quoth (e-mail address removed):
Hello
I am a little bit confused now ? Whats wrong here?

#!/usr/bin/perl

my @bla = ("sdf","sdf","sdf");
print scalar(@bla);
create(@bla);


sub create{
my @arg = shift;
print scalar(@arg);
foreach my $b(@arg){
print "yes";
}
}


In the function the array conists of one element but where are the
other two?
How can I give a function the whole array?

You have: you need to look at the other args:

my @bla = ("sdf", "sdf", "sdf");
create(@bla);

sub create {
my (@arg) = @_;
print scalar @arg;
foreach my $x (@arg) {
print "yes";
}
}

(note you should avoid the variables $a and $b as they are magic and
using them can mess up sort), though if you are really going to process
the whole lot like this it would be easier just to work on @_.

To be more exact, a sub is passed a list. If you pass it one or more
arrays, like this

create( @A, @B );

then they will be 'flattened' into the list. If you want to pass an
array and have it retain its identity, then you need to pass a
reference:

create( \@A );

sub create {
my ($aref) = @_;
print scalar @$aref;
}

See perldocs perlsub and perlreftut (at least).

Ben
 
J

Jürgen Exner

Hello
I am a little bit confused now ? Whats wrong here?

#!/usr/bin/perl

my @bla = ("sdf","sdf","sdf");
print scalar(@bla);
create(@bla);


sub create{
my @arg = shift;
print scalar(@arg);
foreach my $b(@arg){
print "yes";
}
}


In the function the array conists of one element but where are the
other two?

They are still in @_.
How can I give a function the whole array?

You are passing the whole array to the function. You are just never looking
at any element but the first.

jue
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,591
Members
45,102
Latest member
GregoryGri
Top