Can I use Perl unpacking to split a string into vars?

I have an image file name that consists of four parts:

  • $Directory (the directory in which the image exists)
  • $Name (for an art site, this is a link to the name of the picture #)
  • $File (image file name minus extension)
  • $Extension (image extension)
$example 100020003000.png

Which I want to break down accordingly:

$dir=1000 $name=2000 $file=3000 $ext=.png

I was wondering if substr is the best option for breaking up the incoming $example, so I can do things with 4 variables, such as validation / error checking, grabbing the verbose name from its destination $Nameor something else. I found this post:

decompress faster than substr? So, my beginners have a stone tool approach:

my $example = "100020003000.png";
my $dir = substr($example, 0,4);
my $name = substr($example, 5,4);
my $file = substr($example, 9,4);
my $ext = substr($example, 14,3); # will add the the  "." later #

, , , , ?

- , - . - , luv'em, , , .

, , , vars /, , , , .

stackoverflow.com!

+3
5

:

my $example = "100020003000.png";
my ($dir, $name, $file, $ext) = unpack 'A4' x 4, $example;

print "$dir\t$name\t$file\t$ext\n";

:

1000    2000    3000    .png
+11

:

my ($dir, $name, $file, $ext) = $path =~ m:(.*)/(.*)/(.*)\.(.*):;

, :

my ($dir, $name, $file, $ext) = $example =~ m:^(\d{4})(\d{4})(\d{4})\.(.{3})$:;
+5

unpack , , :

my $example = "100020003000.png";
my ($dir, $name, $file, $ext) = $example =~ /(.{4})/g;
+3

, 4 , :

my ($dir, $name, file, $ext) = grep length, split /(....)/, $filename, 4;

, , , , - .

, , :

1. split , . .

qw( a 1 b 2 c 3 ) == split /(\d)/, 'a1b2c3';

2. split 3 , .

qw( a b2c3 ) == split /\d/, 'a1b2c3', 2;

3. , , /(....)/, ( 0). D, F:

 ( '', 'a', '', '1', '', 'b', '', '2' ) == split /(.)/, 'a1b2';
   F    D   F    D   F    D   F    D

4. , 3, :

 ( '', 'a', '', '1', 'b2' ) == split /(.)/, 'a1b2', 3;
   F    D   F    D   F  

5. , ( .jpeg, 4 ):

 ( '', 1000, '', 2000, '', 3000, '.jpeg' ) = split /(....)/, '100020003000.jpeg',4;
   F   D     F   D     F   D     F       

6. 5 , , , , :

(1000, 2000, 3000, '.jpeg') = grep, split/(....)/, '100020003000.jpeg', 4;

, . , . , , .

, . split (, , ), , . : , .

, .

, split.

+1

substr unpack , regex .

The example you provided looked like a fixed layout, but directories are usually separated by file separator (for example, slash for POSIX-style file systems, reverse for MS-DOS, etc.). So you may have a case for both; a regular expression to separate the directory and file name separately (or even directory / name / extension), and then a fixed-length approach for the part of the name itself.

0
source

Source: https://habr.com/ru/post/1719562/


All Articles