consecutive operators and brackets

I'm just trying to learn a bit of Perl and have come across this:

foreach $element (@{$records})
{
    do something;
}

To my newbie eyes, this reads: "for each element in an array named @{$records}, do something" but, since that seems an unlikely name for an array (with "@{$" altogether), I imagine it isn't that simple?

I've also come across "%$" used together. I know % signifies a hash and $ signifies a scalar but don't know what they mean together.

Can anyone shed any light on these?

Answers


In Perl you can have a reference (a pointer) to a data structure:

# an array
my @array;

# a reference to an array
my $ref = \@array;

When you have a reference to be able to use the array you need to dereference it

@{ $ref }

If you need to access an element as in

$array[0]

you can do the same with a reference

${$ref}[0]

The curly brackets {} are optional and you can also use

$$ref[0]
@$ref

but I personally find them less readable.

The same applies to every other type (as %$ for a hash reference).

See man perlref for the details and man perlreftut for a tutorial.

Edit

The arrow operator -> can also be used to dereference an array or an hash

$array_ref->[0]

or

$hash_ref->{key}

See man perlop for details


Need Your Help

For Loop - passing dynamic variables to a click function

javascript jquery for-loop

I have a basic for loop to create a gallery of thumbnail images:

How do I convert a System.Type to its nullable version?

c# .net

Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.