Perl Pro but Java Newbie: Need nudge in proper direction for myfavorite Perl routine in Java

U

/usr/ceo

/usr/ceo said:
I'm using Eclipse (Ganymede) on Mac OS X.  I'll have to try that.  In
general, I'm also learning about the Eclipse-type editing platform,
which also has it's own ecosystem.  NB is based on Eclipse, if I'm not
mistaken, is it not?  I'll have to try the above.  Thanks.

NetBeans is not based on Eclipse, but the two do form a kind of editor
war akin to that of the vi[m]-emacs war. Most features will be found in
both editors; I believe this feature is shared between the two.

It's definitely been well worth my time to stick my head in here. I
have NetBeans something-er-another loaded on my Mac. I should give it
a spin and see which I like better. I was under a false impression
and now I'm curious.

/usr/ceo
 
U

/usr/ceo

The thing is that each language carries its own culture and mindset, of
course.  For example, as a long-time Java programmer I find the roasting very
intense in Perl newsgroups and a tendency to bill Perl as the be-all and
end-all of computer languages.

It gets to be a bit over the top at times yes. A lot of Perl
developers are bigots, yes, prehaps myself included at times, though I
don't find the incinerating on the Perl NGs necessary, as you infer.
People tend to learn better when that aren't tied and burn at the
stake for asking a question. :)
 From a language standpoint, the very things that Perl programmers tend to
excoriate about Java, such as its supposed "verbosity", are actually the very
strengths and design-purpose features of the language.  Java is a language
that respects code maintainers, so things like checked exceptions, strong
typing and even anonymous classes are designed to cause compile-time failures
over run-time failures, to associate logic explicitly with the source code, to
enforce restrictions on code use rather than loosen them, and other things
that run contrary to other languages' core values.  It's all about locking
down a program's behavior inexorably and ineluctably, eliminating bugs before
a production system can ever hate them or a future enhancement can create them.

It's difficult not to fall prey to wanting things to work in one
language as with another you are not only used to but have somewhat
mastered. We warn people about this in the Perl forums; I'm kind
falling prey to it here, I'm finding. A message or two down, someone
has made a very good point for my having traded plus signs (+) for
commas (,), and there is some truth to that.

Truth be told, I adopted puts() from *Ruby* which I really liked
because the newline character at the end was someone intelligently
executed. Not even my Perl routine handles strings exactly as puts()
does in Ruby.

Half of mastering a language, I've always felt, is becoming immersed
in it's pathos. That's why this has been very useful for me. There's
a lot of pathos being provided to me right now and it def. helps speed
the process.

/usr/ceo
 
U

/usr/ceo

/usr/ceo said:
I'm using Eclipse (Ganymede) on Mac OS X.  I'll have to try that.  In
general, I'm also learning about the Eclipse-type editing platform,

I'm sure Eclipse has some abbreviation system, but the one is not based
on the other, and I don't know what the key sequence is for Eclipse.

NetBeans = Sun, Eclipse = IBM.  IBM also makes it's own GUI (SWT) vs.
Sun's Swing, IBM has their own web container (JBoss), etc.  While
competition is good for us programmers, in terms of market I think they
get on like cats and dogs.
  This is mainly for
my own use for now.  

To be a bit less obtuse, there's still problems with your puts() method.
  You can define it to take a variable number of Objects (which includes
Strings), or you can make it take primitives, but you can't mix the two.

   void puts( Object ... o ) {}
   void puts( int ... i ) {}

These are two overloaded puts() methods, but you still can't put ints in
an array of Objects.  Java is more strongly typed than Perl, so it
doesn't allow you to mix the two.  However, with concatenation, you can
mix them.

class TestOut {
   public static void main ( Strings ... args ) {
     int i = 5;
     Object o = new Object();
     javax.swing.JLabel label = new javax.swing.JLabel( "Hi" );
     System.out.println( "I have " + i + " ints and I have " +
                         "\nthis " + o + " thing here and " +
                         "\nI have a JLabel " + label + "." +
                         "\nHave a nice day!"
         );
   }

}

This is more the Java idiom, and it works pretty well.  You're basically
substituting a + for a , which is not any different in typing imo. With
puts(), you still have to type all the parameters, and put a comma after
each one instead of the plus sign I have.

In Java, this is also faster, since calls to the IO system tend to be
slow.  The above code creates one single buffer, and send the whole
thing to the println() method in one call. If you use a for loop in
puts(), you have to make multiple calls, and if you call "new" to make
integers into objects (to pass the ints as parameters with Object[]),
then you're getting even more inefficient.

So I think you should just get used to using the abbreviation (whatever
Eclipse uses instead of "sout") and type a + instead of a comma.  It'll
help you learn Java, and it's no real extra work.  (Note: no code in
this post was tested or compiled.)

All very good things to point out, thanks. I'm becoming more and more
convinced although the exercise has been helpful on more than on
level.

It's not just Java, but all languages that don't allow instring
substitution that I've never really liked. It drives me buts to have
to write plus signs (+) inbetween static strings to concat variables.
I know JavaScript quite well, and I've always disliked this about
JavaScript as well as Visual Basic and VB.Net and others. I just have
an aversion to it and it's not just Perl-influenced. It goes back
farther for me with VMS DCL which allowed the same thing, as does Perl
as does Ruby.

But it's all starting to get OT and philosophical. I believe it may
be better to just acquiesce to it all. The mixed objects example and
all makes it obvious I'm trying to super-impose a methodology from
another language that works quite well into a language that goes about
things a little differently, and it's not necessarily a bad thing.

I'm thinking that the "compile"-phase of Java is what resolves the
different objects in your example above. My "approach" moves it from
compile to runtime. So it seems.

/usr/ceo
 
U

/usr/ceo

You'd presumably have to have the same opinion of C, C#, C++, Pascal, Ada,
Fortran etc. I mean, if you can service the IT niche you're in just using
Perl, that's fine. But you surely realize that you'll never work on a large
project if you only master Perl.

Au contraire. There are a lot of large Perl projects out there. I
think a lot of companies would take issue with that statement such as
Amazon, TicketMaster, WhitePages, IMDb (which is Amazon based),
SixApart and quite a number of others that I know. You can def. work
on large projects with Perl (generally mod_perl, I'll admit) as well
as things like Python, Ruby, and PHP all of which I find quite similar
(well, except maybe Python, through the paradigm still fits here).

I would agree you aren't as *likely* to work on large projects with
Perl (or any of those others) and even less likely in a corporate
environment where I'd guess 90% (in America anyway) are heavily
invested in either JEE or .Net for enterprise applications.

I would definitely hold the same opinion of C# and C++, both of which
are on par with Java (actually, I consider Java the easier if between
Java and C++ -- C# and Java are quite similar in my opinion, and I
happen to like C# because of some of the relaxations it provides.)

I used to be very well versed in Pascal and wrote Pascal for quite
some time in the banking industry. I probably would pull my hair out
now, but I liked it and it served it's purpose then. The anthology of
the languages you've mentioned is quite varied.

I did a lot of C and Assembly language in another lifetime and I still
have an affinity for them both, though I think that's more "mother
duck" and anything else. As an open source developer who occasionally
has to go in and tweek a few things, I can't say I have a loathing for
C though in all fairness, having dived into Java in the last couple of
weeks, I'd have to say Java is definitely an evolutionary step up from
C. Maybe even revolutionary.
I can also assure you that the last time I had to write and use a routine
like the one you describe, in Java, was like never. If it ever did come up
I'd code up something like what was described in other replies, which would
take maybe 15 seconds.

Well, the System.out.println()s are certainly an indication of where I
am right now. I've yet to find a language that didn't start out by
teaching at the most rudimentary level (though to be sure, I'm
inhaling entire chapters generally in less than an hour.) I doubt
I'll be here long...

Say... These connection factories and sessions and message handlers
for writing some MDBs using JMS look interesting...!

See?! :)

/usr/ceo
 
M

Mark Space

/usr/ceo said:
I'm thinking that the "compile"-phase of Java is what resolves the
different objects in your example above. My "approach" moves it from
compile to runtime. So it seems.

I'm getting out of my depth here but I think the answer is yes. The
Java compiler has a few tricks it can do to save typing. That var-arg
statement is one -- it's just implemented with arrays at runtime. Same
with enum, which in Java are just a shorthand class declaration.

Java concatenation is shorthand for invoking a string builder object.

StringBuilder sb = new StringBuilder();
sb.add( "Hi there! Here's my object: " );
sb.add( object );
sb.add( "/nand here is my string: " );
sb.add( string );
sb.add( "/nHave a nice day!" );
System.out.println( sb.toString() );

So the plus-sign is substituting for a full method call. I don't know
if the Java compiler will spot string literal concatenation and make
separate string literals into a single string literal.

There might be a few other cases where the compiler will implicitly call
"new" for you. Autoboxing comes to mind. I can't think of any others
right now in addition to the aforementioned enums and var-agrs.


BTW, if you take NetBeans for a test drive, be sure to use a recent
version. I think 6.1 is the most recent. Lots of nice improvements in
recent months.
 
M

Mark Space

/usr/ceo said:
It's not just Java, but all languages that don't allow instring
substitution that I've never really liked. It drives me buts to have

OK, re-read this and had a thought. What is "in-string substitution"?
You mean like printf?

Geeze, if that's what you wanted, you should have asked:

<http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html>

// Writes a formatted string to System.out.

System.out.format("Local time: %tT", Calendar.getInstance());
// -> "Local time: 13:34:18"

// Writes formatted output to System.err.

System.err.printf("Unable to open file '%1$s': %2$s",
fileName, exception.getMessage());
// -> "Unable to open file 'food': No such file or directory"
 
M

Mark Space

Mark said:
void puts( Object ... o ) {}
void puts( int ... i ) {}

Also, I got to thinking about this, and tested it. I was wrong, Object
.... will allow primitives to be auto-boxed to objects:

class Tests
{

public static void main ( String ... args )
{
//test();
testVarArgs( "One: ", 1, "\nA: ", 'a', "\nTwo: ", 2.0 );
}

static void testVarArgs( Object ... args) {
for( Object o: args )
System.out.print( o );
}

}

OUTPUT:
compile-single:
run-single:
One: 1
A: a
Two: 2.0
BUILD SUCCESSFUL (total time: 1 second)
 
U

/usr/ceo

OK, re-read this and had a thought. What is "in-string substitution"?
You mean like printf?

Geeze, if that's what you wanted, you should have asked:

<http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html>

    // Writes a formatted string to System.out.

    System.out.format("Local time: %tT", Calendar.getInstance());
    // -> "Local time: 13:34:18"

    // Writes formatted output to System.err.

    System.err.printf("Unable to open file '%1$s': %2$s",
                      fileName, exception.getMessage());
    // -> "Unable to open file 'food': No such file or directory"

Instring substitution meaning this:

Ruby:

what="dog"
puts "The #{what} days of summer"

Perl:

$what = 'dog';
print "The $what days of summer\n";

Also known as string interpolation. Love it. Taking an example
someone else left where they spoke rather convincingly that I was
merely substituting commas (,) for pluses (+):

class TestOut {
public static void main ( Strings ... args ) {
int i = 5;
Object o = new Object();
javax.swing.JLabel label = new javax.swing.JLabel( "Hi" );
System.out.println( "I have " + i + " ints and I have " +
"\nthis " + o + " thing here and " +
"\nI have a JLabel " + label + "." +
"\nHave a nice day!"
);
}

}


Perl:

#!/usr/bin/perl
$|++;

use strict;
use warnings qw( all );
use MyOrg::SimpleObject;

my $int = 5;
my $dog = "Fido";
my $o = MyOrg::SimpleObject->new( name => 'Java Crammer' );
$o->name( '/usr/ceo' );

print "I have an int as $int, and my dog's name is $dog, and my name
is ${\ $o->name }...\n";

Like that... Not using format or printf... I don't expect to be able
to do this in Java. That's fine.

/usr/ceo
 
J

Joshua Cranmer

Mark said:
Also, I got to thinking about this, and tested it. I was wrong, Object
... will allow primitives to be auto-boxed to objects:

Autoboxing is pretty smart, except for one (admittedly a bit edgy) case:

List<Integer> list = Arrays.asList('a');

or other cases where you would have to both convert and auto{un}box
(§5.3 doesn't allow both a widening primitive conversion and a
{un}boxing conversion for method invocation conversions).
 
M

Mark Space

/usr/ceo said:
print "I have an int as $int, and my dog's name is $dog, and my name
is ${\ $o->name }...\n";

Ah, I see. Yes you could monkey something up but it's probably not
worth it....



class Tests
{

public static void main( String... args ) throws
IllegalArgumentException,
IllegalAccessException
{
// test();
// testVarArgs( "One: ", 1, "\nA: ", 'a', "\nTwo: ", 2.0 );

class Holder
{

int dogs;
int cats;
}
Holder h = new Holder();
h.dogs = 3;
h.cats = 1;
String s = instring(
"I have $dogs dogs and $cats cats and $fish fish.",
h );
System.out.println( s );
}

static String instring( String s, Object o )
throws IllegalArgumentException,
IllegalAccessException
{
for( Field f : o.getClass().getDeclaredFields() )
{
s = s.replaceAll( "\\$"+f.getName(), f.get( o ).toString() );
}
return s;
}
}

OUTPUT:
I have 3 dogs and 1 cats and $fish fish.
 
M

Mark Space

Joshua said:
Autoboxing is pretty smart, except for one (admittedly a bit edgy) case:

List<Integer> list = Arrays.asList('a');

or other cases where you would have to both convert and auto{un}box
(§5.3 doesn't allow both a widening primitive conversion and a
{un}boxing conversion for method invocation conversions).

That actually might be a good thing. Autoboxing would create two
objects here -- the array and the object -- just to pass one primitive.
It's probably a better idea just to create a method that takes a
single primitive and get the performance boost.

I wonder if autoboxing is smart enough to match things like
public static void testMethod( int i, int i2 ) {}

before it matches "Object... o"
 
J

Joshua Cranmer

Mark said:
That actually might be a good thing. Autoboxing would create two
objects here -- the array and the object -- just to pass one primitive.
It's probably a better idea just to create a method that takes a single
primitive and get the performance boost.

My example was bad then; autoboxing cannot convert a char to an Integer
as a method parameter, variable arity notwithstanding.
I wonder if autoboxing is smart enough to match things like
public static void testMethod( int i, int i2 ) {}

before it matches "Object... o"

Any primitive-level match is matched before autoboxing.
 
M

Mark Space

My example was bad then; autoboxing cannot convert a char to an Integer
as a method parameter, variable arity notwithstanding.

Ah got it. I was just looking through the JLS and I think that might be
covered better in section 5.1.7.

<http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7>

Autoboxing has it's own set of defined conversions, separate from
primitive widening and narrowing. The two don't mix, I guess, and
boxing can only be with the specific type, not with a widened type.
Good point though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top