Reputation: 163
Very frequently I have to do:
#similarly in while (my $val = <$fh>){...}
my $val = <$fh>;
chomp $val;
my $res = `command`;
chomp $res;
I'd rather skip the second line if I could. I see I can use the -l option in my shebang line based on: Is there anything in core Perl to auto-chomp lines from "<>" operator?
Is there something similar for backticks? Or alternately, is there a way to chomp inline that is less verbose?
Upvotes: 2
Views: 402
Reputation: 386396
sub chomper(_) {
my ($line) = @_;
chomp($line) if defined($line);
return $line;
}
while (defined( my $line = chomper(<>) )) {
...
}
Upvotes: 4
Reputation: 2317
You can wrap chomp
around the whole expression
chomp(my $date = `date`);
say $date;
For other suggestions on a sort of "auto-chomp" on filehandles, see this answer.
Update: There's also a Backtick::AutoChomp
module, which is implemented with a source filter.
EDIT
I originally also had the following snippet without actually testing it
while (chomp(my $line = <$fh>)) {
say $line;
}
As per ikegami's comment, this is unreliable and will misbehave in various ways.
Upvotes: 3
Reputation: 1100
Another option to reduce tedium is to learn to love $_
while(<$fh>) {
chomp;
}
local $_ = <$fh>;
chomp;
local $_ = `command`;
chomp;
Same number of lines, but now they are half as long :)
edit: Corrected thanks to @ysth's comment, learnt something new today
Upvotes: 3