Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to truncate a string in Perl - URGENT!!! 2

Status
Not open for further replies.

fyyap

Programmer
Oct 29, 2001
9
SG
Hi,

May I know is there anyway in Perl I can truncate left of my string.

For example, I'll always have these kind of input:
1. /product/fund/include/aaa.cfm
2. /aboutus/include/bbb.cfm
3. /tool/char/include/ccc.cfm

What i wish to do is always TRUNCATE the left of the input, and remain the string start fr include/*.cfm. Fr the example above, the final result will be

1. include/aaa.cfm
2. include/bbb.cfm
3. include/ccc.cfm

Need your help urgently. Many thanks. :)
 
Hi

You can do this by using regular expressions.
Try the following example. Output will be as
shown below the program.

#!/usr/bin/perl

$test[0]="/product/fund/include/aaa.cfm";
$test[1]="/aboutus/include/bbb.cfm";
$test[2]="/tool/char/include/ccc.cfm";

@newarr = ();

for ($i=0; $i<=$#test; $i++)
{
print &quot;\nElement: $i: $test[$i]\n&quot;;
if ($test[$i] =~ /(.*)\/(include\/.*$)/)
{
print &quot;Characters Ignored : $1\n&quot;;
print &quot;Starting with include : $2\n&quot;;
$newarr[$i] = $2;
}
}

foreach $ln (@newarr)
{
print &quot;\nNew list: $ln&quot;;
}

Output
======
Element: 0: /product/fund/include/aaa.cfm
Characters Ignored : /product/fund
Starting with include : include/aaa.cfm

Element: 1: /aboutus/include/bbb.cfm
Characters Ignored : /aboutus
Starting with include : include/bbb.cfm

Element: 2: /tool/char/include/ccc.cfm
Characters Ignored : /tool/char
Starting with include : include/ccc.cfm

New list: include/aaa.cfm
New list: include/bbb.cfm
New list: include/ccc.cfm

Regards
Raj
 
the lazy way to do it

$var = '/product/fund/include/aaa.cfm';

$var =~ /include/;

$output = $& . $';

print &quot;$output\n&quot;;


The two variables $& and $' are the key here.

After a match,
$& contains whatever was matched
$' contains whatever was after the matched string

Oh -- and there's another useful one as well $` will contain whatever was *before* the matched string Mike

&quot;Experience is the comb that Nature gives us, after we are bald.&quot;

Is that a haiku?
I never could get the hang
of writing those things.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top