Perl: moving along input lines using an index

This is a good beginner best practice question in perl. I am new to this language. The question arises:

If I want to process output lines from a program, how can I format the FIRST LINE in a special way?

I think of two possibilities:

1) The flag variable as soon as the loop is executed for the first time. But it will be evaluated for each cycle. BAD Solution

2) An index-based loop (for example, "for"). Then I would start the cycle at i = 1. This solution is much better. The problem is how can I do this?

I just found the code to iterate with the while (<>) construct.

Here you can see better:

$command_string = "par-format 70j p0 s0 < " . $ARGV[0] . "|\n";                                                                                

open DATA, $command_string  or die "Couldn't execute program: $!";

print "\t    <div>&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;|-- <strong>Description</strong></div>\n";
while ( defined( my $line = <DATA> )  ) {
   chomp($line);
   # print "$line\n";
   print "\t    <div>&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;&‎nbsp;|&‎nbsp;&‎nbsp;&‎nbsp;-- " . $line  . "</div>\n";
}

close DATA;

Please feel free to correct any code here, this is my first perl poem.

Thanks!

+3
3

$. $INPUT_LINE_NUMBER ​​ :

while (my $line = <>) {
    if ($. == 1) {
        # do cool stuff here
    }
    # do normal stuff here
}
+8

-,

$line = <DATA>;

.

( ..)

if ($line = <DATA>) {
    ...do special things...
}

while (my $line = <DATA>) {
    ...do regular things...
}

defined(). , , .

+5

" " :

open DATA, $command_string  or die "Couldn't execute program: $!";
  • , , .
  • DATA - , __DATA__ .
  • open my $fh 
    

    .

  • 3 arg open, :

    open my $fh, '<'  , $filename
    open my $fh, '-|' , $command
    open my $fh, '-|' , $command, @args 
    

    Unfortunately, I have yet to figure out how 3-arg with double pipes works. theres' this is IPC :: Open2, but I have not developed how to make good use of it. Suggestions are welcome.

+4
source

Source: https://habr.com/ru/post/1708817/


All Articles