Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Several commands at once?

Status
Not open for further replies.

Tve

Programmer
May 22, 2000
166
FR
Hi,

I've come several times against the following problem: I want to execute several command in one line, but Perl does not seem happy with this. Eg:

From the following string, I want only have C:/temp :

$dir = "C:/temp/test";
@array = split("/",$dir);
pop @array;
$ans = join("/",@array);


I would prefer to use the follwing syntax to avoid creating to many variables:

$dir = "C:/temp/test";
$ans = join("/",pop(split("/",$dir)));

But Perl refuses this syntax: Type of arg 1 to pop must be array....

Am I doing something wrong or does Perl not support this type of syntax?



 
To solve your problem, you can more easily use the following regex:[tt]
my $dir = "C:/dir/subdir/file.ext";
$dir =~ m~(.*/)(.*?)$~; #or with '\\'
my $file = $2;
my $basedir = $1;[/tt]


you can skip assigning to $file if you don't need to. You can also put the '/' inside or outside of the first parentheses, depending on whether or not you want it on the end of your base dir.
 
but as to your actual question, about doing what you were doing, pop only works on data that's already been stored as an array, that means any old list won't do. to do what you want to do, you'll need to create an anonymous reference, then dereference it in the same line, like the following code:
[tt]
print pop( @{[1, 2, 3]} );
[/tt]

you'd replace the '1, 2, 3' with your split code.
the problem is, the return of 'pop' is the element popped, not the rest of the array, so your code won't work even after that. instead of pop, you'll need to splice the array into all but the last element, as in the following:
[tt]
splice(@{[1,2,3]}, 0, (scalar(@{[1,2,3]}) - 1));
[/tt]

but since your using a split as your array, it'll end up having to do that twice, so it'll eat up more process time then a more straight-forward approach. either way, here's what it would look like, whether or not it's a good idea:
[tt]
$ans = join("/",
splice(@{[split("/",$dir)]},
0,
(scalar(@{[split("/",$dir)]}) - 1))
);[/tt]


i tested this, and it works, although i wouldn't recommend it. "If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito."
 
stillflame,


Thanks for effort.


Thierry
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top