Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

one liner for for and if

0 views
Skip to first unread message

Richard Lee

unread,
May 8, 2008, 6:25:55 PM5/8/08
to Perl Beginners
#!/usr/bin/perl

use warnings;
use strict;

my @array = qw/one two three four/;

print "$_\n" for @array last if "$_" eq q/three/;


[root@server tmp]# ./!$
././././testthis2.pl
syntax error at ././././testthis2.pl line 8, near "@array last "
Execution of ././././testthis2.pl aborted due to compilation errors.

Can someone fix my last statement on this program?

I thought maybe this will work but guess not... is there no easy way
to do this?

I don't want to do

for (@array) {
if .......
}
}


just trying to see what the correct format is that for one liner that I
am trying

thanks in advance.

Yitzchok Good

unread,
May 8, 2008, 9:37:11 PM5/8/08
to Richard Lee, Perl Beginners
if ("$_" eq q/three/) {print "$_\n" for @array last};

Rob Dixon

unread,
May 8, 2008, 11:29:21 PM5/8/08
to Perl Beginners, Yitzchok Good
Yitzchok Good wrote:
>
> if ("$_" eq q/three/) {print "$_\n" for @array last};

That won't even compile. Please don't publish nonsense.

Rob

Rob Dixon

unread,
May 8, 2008, 11:26:53 PM5/8/08
to Perl Beginners, Richard Lee

And you want to write it in one line why?

print "$_\n" for grep /one/ .. /three/, @array;

But there's nothing wrong with

foreach (@array) {
print "$_\n";
last if /three/;
}

Rob

Richard Lee

unread,
May 8, 2008, 11:47:36 PM5/8/08
to Rob Dixon, Perl Beginners

use warnings;
use strict;

print "$_\n" for grep /three/, @array;

[root@server tmp]# !$
./test5.pl
three

this works well. However, that goes through entire array.. right?
So there is no true way to squeeze in the ' last ' .. ?

main reason is to see if it's doable(I like some of perl's idioms) and
whether it is possible
The other reason is because I have a big array which I have to look in
by 3 different steps
and I wanted to avoid 3 foreach loop in a row which key depends on
preceding code and wanted to just go
---- simplied version----

my $something = $_ for @array last if "$_" eq q/three/;
my $something1 = $_ for @array last if "$_" eq q/$something/;
my $something2 = $_ for @array last if "$_" eq q/$something1/;

Anyway, I will try your code and report back.

thank you.


0 new messages