dewalla
dewalla

Reputation: 1327

Shortening a string in Perl? (simple)

I have a string:

$path = "C:/Users/user1/tools/test_folder/TEST1_HHH.123"

How do I get Perl to print just the TEST1 part of the string?

ADDITION 3/15/11 -

What if instead of TEST1_HHH.123, the file name if TEST1_2_HHH.123 and I want everything before the _HHH.123? That is the only constant that I want to get rid of (and the other part of the path). THanks –

Upvotes: 1

Views: 366

Answers (3)

ryansstack
ryansstack

Reputation: 1476

if ( $path =~ /.*\/(([^\/]*)_([^\/]*))$/ )
{ 
  my $file = $1; # TEST1_HHH.123
  my $name = $2; # TEST1
  my $suff = $3; # HHH.123
}

Upvotes: 0

Latha Balasundaram
Latha Balasundaram

Reputation: 1

#!/usr/bin/perl
my @test='';
my $test1='';
my $path = "C:/Users/user1/tools/test_folder/TEST1_HHH.123";
@test = split('/',$path);
print "@test\n";
my $test1 ="$test[$#test]";
@res = split('_',$test1);
print "$res[0]";

Upvotes: -1

ikegami
ikegami

Reputation: 385917

This is simple and portable:

use File::Basename qw( basename );
my ($word) = basename($path) =~ /^([^_]+)/;

File::Basename

Upvotes: 15

Related Questions