-3

I have a string which is like ascv/zxc/zxc-asd/zx.java now I wish to cut the string at second / and get the String value as ascv/zxc.

Similarly I will input the special character type and its level. Based on the input it should cut the string. E.g. from first match for character -; or 3rd match of /

Any help is highly appreciated.

Freak
  • 6,786
  • 5
  • 36
  • 54
usercm
  • 45
  • 1
  • 1
  • 4
  • 2
    SO is not a code writing service. Do you care to share what you have tried, why it's not working? See [how to ask](http://stackoverflow.com/questions/how-to-ask). – chrsblck Jun 13 '13 at 06:43
  • I have tried :- $a="ascv/zxc/zxc-asd/zx.java", ($str1,$str2)=split(/\//,$a); output should be ascv/zxc not ascv,zxc – usercm Jun 13 '13 at 07:03
  • 1
    Several ways to do this, `split` is probably the simplest. Just saw your comment edit: use `join` to glue them back together. – cdarke Jun 13 '13 at 07:05

2 Answers2

1

This should help you.

use strict;
use warnings;
use 5.010;

my $str = 'ascv/zxc/zxc-asd/zx.java';

say truncate_at($str, '/', 1);
say truncate_at($str, '/', 2);
say truncate_at($str, '/', 3);
say truncate_at($str, '/', 4);
say truncate_at($str, '-', 1);

sub truncate_at {

  my ($str, $sep, $n) = @_;
  my @offsets;

  push @offsets, $-[0] while $str =~ m|\Q$sep|g;
  substr($str, $offsets[$n-1]) = '' if $n <= @offsets;

  $str;
}

output

ascv
ascv/zxc
ascv/zxc/zxc-asd
ascv/zxc/zxc-asd/zx.java
ascv/zxc/zxc
Borodin
  • 126,100
  • 9
  • 70
  • 144
0

How about:

my $str = 'ascv/zxc/zxc-asd/zx.java';
$str =~ s#^([^/]+/[^/]+).*#$1#;
say $str;

output:

ascv/zxc
Toto
  • 89,455
  • 62
  • 89
  • 125
  • thanks but it can vary upto what level i need to match , it can be match first special character(/) or match 4th, its given by argument.instance- cut a string before 3rd "/" match, cut a string before 5th match of "/" – usercm Jun 13 '13 at 08:58