Jakeimo
Jakeimo

Reputation: 61

Incrementing by line or by whitespace in perl

I want to read a file that can come in two types of format:

x 512 512 255

and

x
512 512
255

I want to store each of these as individual variables. Because of the two types of formats, I can't simply chuck the input of each line in a variable.
Is there any way I can increment through a file by whitespace and by newline as well?

Here is my code that assumes the second format only.

#!/usr/bin/perl -w
use strict;

my $fileType;
my $fileWidth;
my $fileHeight;
my @lineTwo;
my $inputFile = $ARGV[0];

open(my $file, "<", $inputFile) or die;

while (my $line = <$file>){
    if($. == 1){
        $fileType = $line;
        chomp $fileType;
    }elsif($. == 2){
        @lineTwo = split(/\s/,$line);
    $fileWidth = $lineTwo[0];
        $fileHeight = $lineTwo[1];
        }
    last if $. == 2;

}

print "This file is a $fileType file\n";
print "Width of image = $fileWidth\n";
print "Height of image = $fileHeight\n";

Upvotes: 0

Views: 46

Answers (2)

Borodin
Borodin

Reputation: 126722

Just keep fetching fields from the file until you have three or more.

There is no need to explicitly open files passed as parameters on the command line, as <> will implicitly open and read through them all sequentially.

use strict;
use warnings;

my @data;

while (<>) {
  push @data, split;
  last if @data >= 3;
}

my ($type, $width, $height) = @data;
print "This is a $type file\n";
print "Width of image  = $width\n";
print "Height of image = $height\n";

output

This is a x file
Width of image  = 512
Height of image = 512

Upvotes: 4

Miller
Miller

Reputation: 35198

Just slurp the file and split on whitespace (which will include either spaces or newlines):

#!/usr/bin/perl -w

use strict;
use warnings;
use autodie;

my $inputFile = shift;

my ($fileType, $fileWidth, $fileHeight) = split /\s+/, do {
    local $/;
    open my $fh, '<', $inputFile;
    <$fh>;
};

print "This file is a $fileType file\n";
print "Width of image = $fileWidth\n";
print "Height of image = $fileHeight\n";

All this can actually be compressed down to the following if you're comfortable with perl's more advanced tools:

#!/usr/bin/perl -w

use strict;
use warnings;

my ($fileType, $fileWidth, $fileHeight) = split ' ', do {
    local $/;
    <>;
};

Upvotes: 2

Related Questions