Richard Lee wrote:
one more question on reference,
if say you have sub as below
Your code is badly wrong. Please let me correct it first.
my @arrayref;
sub do_something {
my $something = @_;
That will set $something to the number of parameters passed in @_
To retrieve the first parameter you should write
my ($something) = @_;
or
my $something = shift;
open FILE, "$something", or die;
You should not quote scalar variables unless you know what it does and have a
reason to do it. Also the it is far better and safer to use lexical file handles
and the three-parameter form of open, and you should incorporate the $! variable
into the die string so that it is clear why the open has failed.
open my $file, '<', $something or die $!;
while (<FILE>) {
while (<$file>) {
if you are using my proposed change.
my @array = map (split /,/)[1,2,3,5];
That will probably not compile. You are calling
map(split /,/)
and map requires either a block or an expression as its first parameter,
followed by a list to map. You mean simply
my @array = (split /,/)[1,2,3,5];
push @arrayref, [EMAIL PROTECTED];
}
close FILE;
If you use a lexical file handle $file then it will be closed implicitly when it
goes out of scope at the end of the subroutine. There is no need for an explicit
call to close.
}
my @arrayref_copy = do_something($something);
Let's for a moment forget about my inefficient style and just look at
the last step. If I wanted to use @arrayref_copy and pass it into another
subroutine,should I reference them again?(if file itself was pretty big?)
another_sub([EMAIL PROTECTED]); <-- is this the right thing to do? or is
this redundant since array is already collection of reference?
sub another_sub {
}
Yes that would be fine. It helps because you're not copying all the references
to a second list. But I would go a step further and pass it back from the first
subroutine as a reference to an array. Like this
sub read_file {
my $name = shift;
open my $fh, '<', $name or die $!;
my @data;
while (<$fh>) {
my @record = (split /,/)[1, 2, 3, 5];
push @data, [EMAIL PROTECTED];
}
return [EMAIL PROTECTED];
}
and then you can write
my $data = read_file('filename');
my $result = another_sub($data);
and so on.
HTH,
Rob