0

How can I make this piece of my code terser (in one line) but still understandable.

 ($ext) = $ARGV[0] =~ /(\.[^.]+)$/;
 $ext=~s/^.//s;
 $ext=uc $ext;

It gets the file extensions, remove the dot and then uppercase it.

in: asldaldjlajdlk.torrent
out: TORRENT
Ali Abbasinasab
  • 382
  • 3
  • 13

5 Answers5

4

I think I'd probably use something like:

my $ext = ($ARGV[0] =~ /\.(\w+)$/) ? uc($1) : undef;

Adjust undef to be whatever you'd like the default value of $ext to be when the regexp fails to match.

tobyink
  • 13,478
  • 1
  • 23
  • 35
3

You've chosen a pattern that will not always match.

I therefore suggest using a ternary to be able to explicitly specify your undefined value.

my $ext = $ARGV[0] =~ /\.([^.]+)$/ ? uc($1) : '';
Miller
  • 34,962
  • 4
  • 39
  • 60
1

$v is your input

($m = uc $v) =~ s/(\w+)\.(\w+)/$2/g;
pkm
  • 2,683
  • 2
  • 29
  • 44
0

Removing my answer, this is discussed here: Inline regex replacement in perl

The furthest I got was this:

($ext = uc $ARGV[0]) =~ s/^.*\.([^.]+)$/$1/;

Community
  • 1
  • 1
Alien Life Form
  • 581
  • 1
  • 7
  • 15
0

I think I would ignore the possibility that a file name may not contain a dot, and write

(my $ext = uc shift) =~ s/.*\.//
  • If there is a dot in the name, this leaves $ext set to the upper-cased file extension (everything after the last dot).

  • Otherwise $ext is set to the whole upper-cased file name.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Borodin
  • 126,100
  • 9
  • 70
  • 144