Notice that nowadays (unless you have serious backward compatibility issues) it is recommended to#!/usr/bin/perl -w use strict;
instead. Since when I made a similar remark somebody popped out asking why I thought the latter was a better alternative, I'll point out in advance that no, I'm not explaining it. perldoc warnings and perldoc perlrun give some clues about it.use warnings;
my $jpg = shift or die "$!\n";Huh?!? $! is meaningful only after a failure of a system call (well, "system library"). At this point it may be anything...
Please, do not misunderstand me: I know that this is a minimal example, but why do you put the return values of your sub into an array only to later use its entries separately? I.e., wouldn't havemy $data = get_file($jpg); my @res = sizeJPG($data); print "$jpg width $res[0] height $res[1]\n";
been clearer?my $data = get_file($jpg); my ($h,$v) = sizeJPG($data); print "$jpg width $h height $v\n";
Also, in case the regex below is not matched, the return values will be undef, and this will issue a warning in the print statement above. And if you locally disable 'uninitialized' warnings, then you'll get an IMHO inconsistent output. You may want to treat this case in a different way...
I like to dosub sizeJPG { return unless $_[0]; my ( $width, $height ); ( $height, $width ) = unpack( "nn", $1 ) if $_[0] =~ /\xFF\xC0...(....)/; return ( $width, $height ); }
if possible, but that's just a personal preference.local $_=shift;
As a general remark you can also use the return value of the match operator, but indeed in this case it can be slightly awkward:
and it will also issue a warning if the regex is not matched. So a possibly better solution may be:my ($width,$height)=unpack "nn", (/\xFF\xC0...(....)/)[0];
Let's go on...my ($width,$height)=unpack "nn", /\xFF\xC0...(....)/ ? $1 : ''; # or "\0" x 4, maybe?
Why notsub get_file { open FILE, $_[0] or die $!; binmode FILE; local $/; my $data = <FILE>; close FILE; return $data; }
instead?sub get_file { local $/; open my $fh, '<:raw', shift or die $!; <$fh>; }
(But then I'd probably use a do block. In the meantime we continue to wait for Perl6's .slurp!!)
In reply to Re^2: getting the dimensions of a picture (jpeg)
by blazar
in thread getting the dimensions of a picture (jpeg)
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |