I am trying to print out a section of a file begining at the start and printng until a character is found.
My code and input file are below. This code is printing out every line except for the line with the character which is not what I want the out put should be a file with numbers 1-4.
Input file
1
2
3
4
*5
6
7
8
Code
while(<FILE>)
{
until(/\*/) {
print "\n$_\n";
last;
}
}
close(FILE);
Please provide a correction to the code or a better method.
Thanks
$
$
$ cat f1
1
2
3
4
*5
6
7
8
$
$ perl -lne '$x=1 if /\*/; print if not $x' f1
1
2
3
4
$
$
tyler_durden
Thanks tyler_durden, can you please explain your code I think your seting $x to true if the line contains "*" and if not then it's false?
---------- Post updated at 12:13 PM ---------- Previous update was at 12:06 PM ----------
I think I got the concept. Set a variable to 1 if you hit this character if the variable is 0 by default then print
while(<FILE>)
{
$x=1 if(/\*/);
if($x==0){print;}
}
Thanks
$x is undefined at that point, but the equality condition is true which is why it prints.
You could do the same without a sentinel variable.
#perl -w
open(F, "f1") or die "Can't open f1: $!";
while (<F>) {
unless (/\*/) {
print;
} else {
last;
}
}
close(F) or die "Can't close f1: $!";
or
#perl -w
open(F, "f1") or die "Can't open f1: $!";
$_ = <F>;
until (/\*/) {
print;
$_ = <F>;
}
close(F) or die "Can't close f1: $!";
come to mind.
tyler_durden