tags:

views:

127

answers:

5

In my Excel sheet with column Changeset I am getting the changeset like:

C:\ccviews\hgdasdff-9302\dfcsz\ahgrt\kjhssl\ASGHLS@@\main\ajsdkljlat\hahdasdhfk\1\test.txt\sub\hsdaklfl\3

I need to use split function in a Perl script so that there will be two ouput (input as the above string)

  • the part before @@ (e.g-here C:\ccviews\hgdasdff-9302\dfcsz\ahgrt\kjhssl\ASGHLS)
  • the last character of the string (e.g-here 3)
+5  A: 

This sounds too complicated for a regular split, you need an ordinary regex like this:

my ($first, $second) = / ^ (.+?) @@ .* (.) $ /x;
Leon Timmermans
This could also be wrapped in a conditional so as to warn if fed any non-matching input, e.g.: `if ( ! /^(.+)?@@.*(.)$/ ) { warn( "Unknown line format: \"$_\"" ); }` - might also be worth adding a quick explanation what the non-greedy expression does, after all you're using the `/x` operator, which allows you to spread the regexp over multiple lines and add comments
PP
Yeah, that would be a good idea
Leon Timmermans
+2  A: 

I think this is what you want, or do you need it all in one statement?

 my ($before, $after) = split '@@', $input;
 my $last_char = substr($after, -1, 1);
datageist
A: 

Adding to the two answers already, you can try the following using only split function:

$s = 'C:\ccviews\hgdasdff-9302\dfcsz\ahgrt\kjhssl\ASGHLS@@\main\ajsdkljlat\hahdasdhfk\1\test.txt\sub\hsdaklfl\3';

@temp = split/@@/,$s;
$part1 = $temp[0]; # C:\ccviews\hgdasdff-9302\dfcsz\ahgrt\kjhssl\ASGHLS

@temp = split//,$s;
$part2 = $temp[-1]; # 3
codaddict
A: 

The split based solution, as requested by the OP:

my @a = split /@@.*?(.)$/, $s;

How it works:

1) The string is split into 2 parts: everything before '@@' and an empty string. The empty trailing one is deleted by split.

2) As the pattern contains parentheses, additional list element is created from the matching substring in the delimiter.

eugene y
Please explain why.
PP
@PP: you are welcome
eugene y
Thanks a lot Guys..it really helped me out.Works just superbly..
devtech
+2  A: 

From Regular Expression Mastery by Mark Dominus:

Randal's Rule

Use capturing or m//g when you know what you want to keep.

Use split when you know what you want to throw away.

Randal Schwartz

You know what you want to keep, so use m//g as in Leon Timmermans's answer.

Greg Bacon
Every gambler knows that the secret to survivin' is knowin' what to throw away and knowin' what to keep
JoelFan