Gerryjun has asked for the wisdom of the Perl Monks concerning the following question:

my question is simple i have codded my file name in to numbers like Exp. 0092042095432.dat the first 4 digits represents in formations, and so on! how do i chop-up the file name to get the information? i dont want to put the info inside the file! i use it as my naming convention, so i want to know what that file is!

Replies are listed 'Best First'.
Re: choping a word!
by dga (Hermit) on Aug 28, 2001 at 20:19 UTC

    You could use substr or unpack

    use strict; my $filename="0092042095432.dat"; #get this in as desired #THEN with substr my $fourchars=substr($filename,0,4); # OR with unpack my $fourchars=unpack("A4",$filename); #THEN if you want each character you can my @chars=split('',$fourchars);

    Now you have an array chars with the values (0, 0, 9, 2);

Re: choping a word!
by grinder (Bishop) on Aug 28, 2001 at 20:22 UTC

    You want to read up on some basic documentation first, such as substr. To get the first four letters of your filename, you would do something like:

    my $filename = '0092042095432.dat'; my $part = substr( $filename, 0, 4 );

    Simple questions like this are best asked in the Chatterbox.

    --
    g r i n d e r
Re: choping a word!
by dvergin (Monsignor) on Aug 28, 2001 at 20:33 UTC
    It's not clear whether your "...and so on" means that you want to grab several pieces of information from each filename or whether you just mean more filenames with one thing to grab each time.

    To take the case that the others have not answered so far, let's assume for a moment that the number of digits is always exactly the same each time and that you want to retrieve several bits of data from the filename. Try a regex. Long form:

    use strict; my ($this, $that, $tother, $twix); my $fname = "0092042095432.dat"; if ($fname =~ /^(\d{4})(\d{3})(\d{3})(\d{3})/) { ($this, $that, $tother, $twix) = ($1,$2,$3,$4); } print "$this $that $tother $twix\n"; # ...or whatever
    Or... more succinctly and idiomatically:
    ($this, $that, $tother, $twix) = $fname =~ /^(\d{4})(\d{3})(\d{3})(\d{3})/; print "$this $that $tother $twix\n"; # ...or whatever