develooper Front page | perl.beginners | Postings from May 2008

Re: one liner for for and if

Thread Previous | Thread Next
From:
Rob Dixon
Date:
May 8, 2008 20:27
Subject:
Re: one liner for for and if
Richard Lee wrote:
> #!/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

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

Thread Previous | Thread Next


Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About