Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Extract string from rear of string

by thunders (Priest)
on Dec 29, 2001 at 02:52 UTC ( [id://135006]=note: print w/replies, xml ) Need Help??


in reply to Extract string from rear of string

Update: Juerd is correct in his post below. I made a mistake in my post regarding the split operator. I have corrected this.

Here is an example of File::Basename, applied to the current directory. This is not perfect, but should get you started.
#/usr/bin/perl -w use File::Basename; use strict; my @files = <*>; foreach my $file (@files) { my ($name,$dir,$type) = fileparse($file,'\..*'); print sprintf("file= %30s", $name), sprintf(" ext= %10s", $type), +"\n"; }

you can refine this by crafting a better regex as the second argument to fileparse. This module is overkill unless you are dealing with full filepaths. for a single directory you could just use
my($filename,$ext) = split(/\./,$file);
or something similar.

Replies are listed 'Best First'.
Re: Re: Extract string from rear of string
by Juerd (Abbot) on Dec 29, 2001 at 03:54 UTC

    print sprintf("file= %30s", $name), sprintf(" ext= %10s", $type),"\n";
    Personally, I'd use:
    printf "file = %30s ext= %10s\n", $name, $type;

    my($filename,$ext) = split('\..*',$file);
    While this is valid syntax, using a string as split's first argument might be confusing to beginners. Every string that is not a single space (\x20) is interpreted as a regex. Using slashes or another m// makes your intention clear.
    my ($filename, $ext) = split /\..*/, $file;

    Splitting on /\..*/ would return ('foo', undef) for 'foo.bar'.
    Splitting on /\./ would probably fix this, but you don't want ('foo', 'bar', 'baz') or (using a limit) ('foo', 'bar.baz').
    So using a regex without split would probably be best:

    my ($filename, $ext) = $file =~ /^(.+)(?:\.(.*))?$/s
    (The first .+ will grab as much as it can, because it is greedy. The /s was added just in case someone has a linefeed in his filename, the anchors are there just to clarify the code, they don't serve a real. I used .+ for dotfiles (filenames beginning with a dot are hidden files in *nix). The extention part is optional ( (?:)? ) because not all files have an extention.)

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://135006]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-23 17:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found