Tomer Schweid
Tomer Schweid

Reputation: 355

perl unexpected split behaviour

I'm trying to write down a perl script which will be able to distinguish between the different labels of my drives to a specific one and then do something in that specific drive.
I am running Active Perl 5.16.3.1603 on a windows XP computer.

Here is what I wrote:

use strict;
$_ = `fsutil fsinfo drives`;
my @drives = split;
my @labels;
for (@drives)
{
    push @labels, `label $_`;
}
for (@labels)
{
    print "$_\n";
}

The for loop at the end is a print check.
I get nothing as result. I tried to check it in another way:

use strict;
$_ = `fsutil fsinfo drives`;

print;
print "\n";
print join "\n", split;

My result is:

Drives: C:\ D:\ E:\ G:\

Drives:
C:\ D:\ E:\ G:\

Why does split act not the way it should?
I tried to do split " ", split / / and split /\s+/.
They all end up with the same output.

If someone knows why it happens and how to make it go away, please share.
Thanks in advance.

Upvotes: 1

Views: 128

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

A hexdump - as advised by DavidO

00000000h: 0D 0A 44 72 69 76 65 73 3A 20 41 3A 5C 00 43 3A ; ..Drives: A:\.C:
00000010h: 5C 00 44 3A 5C 00 45 3A 5C 00 4D 3A 5C 00 0D 0A ; \.D:\.E:\.M:\...

shows that you get more (leading/trailing CrLf) and other (00 instead of 20) whitespace than you probably expected (tested under Win XP).

So to get a list of drive letters, a positive regular expression may be a better approach:

$ my $res = `fsutil fsinfo drives`;

Drives: A:\ C:\ D:\ E:\ M:\

$ $res =~ /\b\w:/g;
$ARRAY1 = [
            'A:',
            'C:',
            'D:',
            'E:',
            'M:'
          ];

Update wrt comment:

  1. A hexdump gives you a clear view of binary data; I used it to show what you really get when you call fsutil.
  2. I mentioned XP, because I can't rule out that fsutil returns a string with different delimiters on other versions of windows.
  3. By using a regular expression that cuts what you want (drive letters) instead of what may lurk in between, I tried to propose a solution that works even when Mr. Gates changes the zeros to spaces, tabs, or ", ".
  4. Could you provide a link that explaines the meaning of "other stuff" to the uninitiated?

Upvotes: 3

Related Questions