On Jul 28, Tara Calishain said:

>At 01:22 PM 7/28/2003, you wrote:
>
>>>      What perl function can i use to extract a
>>> sub-string from a string.
>>
>>$string = 'myfile.txt';
>>
>>$string =~ m/^(\w+)\.txt$/;
>
>When I saw this question I immediately thought
>
>my $string = "myfile.txt";
>my $substring = substr($string, 0, 6);
>print $substring;

That's *awfully* specific.  "myfile.txt" was clearly just an example of a
filename.  If the value of $string were "avacado.html", your substr()
approach would return only "avacad".  Granted, the given regex is awfully
specific too -- it requires a filename made up ONLY of word characters
followed by ".txt".

>my $string = "myfile.txt";
>my @stringwords = split(/\./, $string);
>print $stringwords[0];

I'd probably do

  my ($prefix) = split /\./, $string;

if I didn't need anything after the first ".".

>Can you address why you'd want to use RegEx instead of one of the above
>choices? I know there are lots and lots of different ways to do things in
>Perl; I'm just trying to get a handle on why sometimes it's better to do
>things one way than another way.

Well, split() is very direct.  If the filename were "this.txt.old", and we
wanted to get "this.txt" (as opposed to just "this"), split() would
require additional work:

  my @parts = split /\./, $string;
  pop @parts;
  my $name = join ".", @parts;

>... the answer "because that's how I usually do it and it's habitual" is
>completely legit. :->

I'd suggest using the File::Basename module.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to