我可以使用 Perl 的解包将字符串分解为 vars 吗? [英] Can I use Perl's unpack to break up a string into vars?

查看:37
本文介绍了我可以使用 Perl 的解包将字符串分解为 vars 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由四部分组成的图像文件名:

  1. $Directory(图片所在的目录)
  2. $Name(对于艺术网站,这是画名参考#)
  3. $File(图片文件名减去扩展名)
  4. $Extension(图片扩展)

$example 100020003000.png

我希望相应地分解:

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

我想知道 substr 是否是分解传入 $example 的最佳选择,以便我可以使用 4 个变量进行操作,例如验证/错误检查,从其 中获取详细名称$Name 赋值或其他.我找到了这个帖子:

解压速度比 substr 快吗?所以,在我的初学者石器"方法中:

my $example = "100020003000.png";我的 $dir = substr($example, 0,4);我的 $name = substr($example, 5,4);我的 $file = substr($example, 9,4);我的 $ext = substr($example, 14,3);# 将添加."之后 #

那么,我可以使用解包,或者甚至是另一种更有效的方法吗?

我还想避免加载任何模块,除非这样做会因某种原因使用更少的资源.Mods 是我喜欢的很棒的工具,但我认为这里没有必要.

我意识到我可能应该将变量推入数组/哈希,但是,我真的是这里的初学者,我需要进一步说明如何做到这一点以及如何将它们拉回来.

感谢 stackoverflow.com 的所有人!

解决方案

绝对:

my $example = "100020003000.png";我的 ($dir, $name, $file, $ext) = 解包 'A4' x 4, $example;打印 "$dir\t$name\t$file\t$ext\n";

输出:

<前>1000 2000 3000 .png

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

  1. $Directory (the directory where the image exists)
  2. $Name (for a art site, this is the paintings name reference #)
  3. $File (the images file name minus extension)
  4. $Extension (the images extension)

$example 100020003000.png

Which I desire to be broken down accordingly:

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

I was wondering if substr was the best option in breaking up the incoming $example so I can do stuff with the 4 variables like validation/error checking, grabbing the verbose name from its $Name assignment or whatever. I found this post:

is unpack faster than substr? So, in my beginners "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 #

So, can I use unpack, or maybe even another approach that would be more efficient?

I would also like to avoid loading any modules unless doing so would use less resources for some reason. Mods are great tools I luv'em but, I think not necessary here.

I realize I should probably push the vars into an array/hash but, I am really a beginner here and I would need further instruction on how to do that and how to pull them back out.

Thanks to everyone at stackoverflow.com!

解决方案

Absolutely:

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

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

Output:

1000    2000    3000    .png

这篇关于我可以使用 Perl 的解包将字符串分解为 vars 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆