Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm using a module (Mail::Audit) that returns a reference to an array of lines. I can't figure out to print out or gain access to the lines being referenced. I'm tried writing the below code with no luck. Any suggestions?
#@body is the reference to the array of lines my @body=$item->body; print @body; #also tried foreach my $line (@body){ print $line; }

Replies are listed 'Best First'.
•Re: Reference to an array
by merlyn (Sage) on Jun 11, 2002 at 14:35 UTC
Re: Reference to an array
by Abigail-II (Bishop) on Jun 11, 2002 at 14:54 UTC
    The syntax rule in Perl is that anywhere where you write @arrayname you may replace arrayname with a block whose result is a reference to an array.

    So, since $item -> body is an expression returning an array, we can write @{$item -> body}. And that's the array you want.

    Abigail

Re: Reference to an array
by little (Curate) on Jun 11, 2002 at 14:41 UTC
    See perlman:perlref.
    # if $body is a ref to an array @deRefArray = @{$body};

    Have a nice day
    All decision is left to your taste
Re: Reference to an array
by Jenda (Abbot) on Jun 11, 2002 at 14:56 UTC

    There are basicaly two ways you can solve it.

    First, you can dereference the array as soon as you get it from ->body() ... but in that case you are forcing Perl to create a copy of the array for you. Or

    Second, you may keep the reference and use it:

    #$body is the reference to the array of lines my $body=$item->body; print @$body; #or foreach my $line (@$body){ print $line; }
    If you wanted to access for example the 5th line of the body you could use :
    print "5th line=$body->[4]\n";

      Jenda@Krynicky.cz

Re: Reference to an array
by vkroll (Novice) on Jun 11, 2002 at 17:27 UTC
    If it's really a ref to an array you have to dereference it.
    Try:
    my $body = $item->body; # ^ It's important foreach my $line(@$body) { print $line; } ## or for debugging use Data::Dumper; print STDERR Dumper $body;
    HTH
    Volker