Need help from Perl expert

T

t53864

I am new to Perl and currently trying to debug a Perl script.
I encountered a line which I have no clue what it is trying to do.
Hope some experts here can help me out.

grep { ${ $_ }[0] =~ /^$ptype/ } @ports

Thanks in advance,

TL
 
B

Brian Wakem

I am new to Perl and currently trying to debug a Perl script.
I encountered a line which I have no clue what it is trying to do.
Hope some experts here can help me out.

grep { ${ $_ }[0] =~ /^$ptype/ } @ports

Thanks in advance,

TL


I don't qualify as an expert, but perhaps this will shed some light.


#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

my @ports = (
[ 'Southampton', 'Hampshire' ],
[ 'Portsmouth', 'Hampshire' ],
[ 'Dover', 'Kent' ],
);

my $ptype = 'S|P';

@ports = grep { ${ $_ }[0] =~ /^$ptype/ } @ports;

print Dumper \@ports;


-----------------------------


$ perl tmp56.pl
$VAR1 = [
[
'Southampton',
'Hampshire'
],
[
'Portsmouth',
'Hampshire'
]
];
 
P

Paul Lalli

I am new to Perl and currently trying to debug a Perl script.
I encountered a line which I have no clue what it is trying to do.
Hope some experts here can help me out.

grep { ${ $_ }[0] =~ /^$ptype/ } @ports

You don't need an expert. You just need a clearer understanding of the
pieces of the language involved:

grep { EXPR } LIST
returns all those elements of LIST (@ports, in this case) for which
EXPR is true, setting each element of LIST to $_ in EXPR

EXPR =~ /^$ptype/
returns true if the string contained in EXPR contains the substring
"beginning of string, followed by the contents of $ptype"

${ REF }[0]
is the first element of the array referenced by REF

$_
as we already said, will be aliased to each element of @ports

Putting it all together:

Loop through each member of @ports. For each member, look at the first
element of the array that member references. If that element contains
the variable $ptype at it's start, add this member of @ports to the
list of values returned by the entire expression.

For more information:
perldoc -f grep
perldoc perlref
perldoc perlre

Hope this helps,
Paul Lalli
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top